Search code examples
phpfopendelimiterfgetcsv

How do I enclose a field with double quotes, using fgetcsv


I have this csv:

1629311007-1407,"[{""cats"":""Cat1""},{""cats"":""Cat2""}]",[],title

<?php 
header('Content-Type: text/html; charset=UTF-8');
$local_file = 'data.csv';
echo count(file($local_file)).' itens';

$fileHandle = fopen($local_file, "r");

while (($row = fgetcsv($fileHandle, 0, ',')) !== FALSE) {

  echo $row[0].'<br>';
  echo $row[1].'<br>';
  echo $row[2].'<br>';
 

}
?>

Output must be:

1629311007-1407
[{""cats"":""Cat1""},{""cats"":""Cat2""}]
title

But it's coming out like this

1629311007-1407
"[{""cats"":""Cat1""}
{""cats"":""Cat2""}]"

How can I adjust?


Solution

  • ($fileHandle,0,',','"');
    

    Add the forth parameter in fgetcsv which will not break the comma between your strings that are between double quotes. So a comma between double quotes will be ignored and considered 1 field.