Consider s CSV file like this
item1,"description 1" item2,"description 2" item3,"description 3 description 3 continues on new line" item4,"description 4"
which should be parsed like this
item1,"description 1" item2,"description 2" item3,"description 3 description 3 continues on new line" item4,"description 4"
Is there a way to parse this CSV in PHP which has multiline values?
In order to process the CSV file with values in rows scattered across multiple lines, use option("multiLine",true) .
PHP fgetcsv() Function$file = fopen("contacts. csv","r"); print_r(fgetcsv($file)); fclose($file);
Use built-in csv module csv module can be used to read CSV files directly. It can be used to both read and write CSV files.
Here are some working examples how to do it. I am using fgetcsv:
CSV in string variable $CsvString:
$fp = tmpfile(); fwrite($fp, $CsvString); rewind($fp); //rewind to process CSV while (($row = fgetcsv($fp, 0)) !== FALSE) { print_r($row); }
CSV in file:
if (($handle = fopen("test.csv", "r")) !== FALSE) { while (($row = fgetcsv($handle, 0, ",")) !== FALSE) { print_r($row); } fclose($handle); }
fgetcsv
should be able to properly parse this.
I wouldn't recommend doing this by hand anyway, there are many such gotchas in parsing CSV.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With