Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse csv in PHP having multiline data in a column

Tags:

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?

like image 961
Ergec Avatar asked Jan 19 '11 07:01

Ergec


People also ask

Can CSV have multiple lines?

In order to process the CSV file with values in rows scattered across multiple lines, use option("multiLine",true) .

How to use fgetcsv in PHP?

PHP fgetcsv() Function$file = fopen("contacts. csv","r"); print_r(fgetcsv($file)); fclose($file);

How do I read a multiLine csv file in Python?

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.


2 Answers

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); } 
like image 193
StanleyD Avatar answered Sep 18 '22 17:09

StanleyD


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.

like image 23
deceze Avatar answered Sep 20 '22 17:09

deceze