Read csv file that has header and column with commas

Asked

Viewed 476 times

0

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

How do I make my code ignore column 4 or put the text of column 4 only in an index?

That’s 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;

}

2 answers

1

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

Example of a comma line where 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 str_getcsv function has 1 mandatory parameter and three options, one of which is Enclosure

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

Check which Enclosure is used in your csv, it may be another character other than "

Comma fields should always be read wrong if the delimiter is a comma have an Enclosure.

If your csv’s Enclosure is " then $delimiter is a comma and the escape may simplify the call from the str_getcsv function to

str_getcsv($input=$line)

Finally take into account 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 = "\\" ]]] )

-1

The text of your header should contain quotes so that it works with the comma, but the recommended is that the header is not a text but a word.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.