Read csv file that has header and column with commas

0

I'm trying to read a ** csv file and save it to an array **, but the problem is that the fourth column of the csv file I'm reading has a comma separated text, and this causes when I read the csv file, php separates the text from column 4 into different indexes of the array.

How do I get my code to ignore column 4 or to place column 4 text only in an index?

This is my code to read the file:

function readCsv($fileName)
{
         if(!file_exists($fileName) || !is_readable($fileName)) return false;

         $header = null;
         $data = array();
         $lines = file($fileName);
         foreach($lines as $line) {
             $values = str_getcsv($line, ',', '\');
            if(!$header)
                 $header = $values;
             else 
                 $data[] = array_combine($header, $values);
         }
         return $data;

}
    
asked by anonymous 28.08.2018 / 05:25

2 answers

1

If the field of your csv contains commas the same must have an enclosure character

Example of a line with commas where the enclosure is the character "

Jim Grayson, Senior Manager, (555) 761-2385, "Spoke Tuesday, he's interested"

If this does not happen csv is not created correctly. The function str_getcsv has 1 mandatory parameter and 3 optional, one of which is enclosure

By "default" of the function if the $ enclosure parameter is not passed it assumes the value of "

Check which enclosure is used in your csv, may be something other than "

Fields with a comma should always have a delimiter where a comma has an enclosure if it does not, it will be read incorrectly.

If the enclosure of your csv is ", $ delimiter is a comma and escape \ may simplify the call of the function str_getcsv to

str_getcsv($input=$line)

Finally, consider the order in which the parameters are passed to the str_getcsv function, according to the manual:

array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]] )
    
28.08.2018 / 10:24
-1

Your header text should contain quotation marks so it works with the comma, but it is recommended that the header be not text but a word.

    
28.08.2018 / 08:26