Undefined index, while trying to access csv column

378 views Asked by At

My csv file looks like this:

"Col1";"Col2";"Col3";Col4;Col5;
2869;"=""510015171""";"=""7393077918""";Test;"Name";

After executing this code:

        $reader = Reader::createFromPath('/file.csv');
        $reader->setDelimiter(';');

        $records = $reader->getRecords();
        foreach ($records as $record) {
            dump($record['Col1']);
        }

I am getting the following error:

WARNING   [php] Notice: Undefined index: Col1

The format of CSV file is correct because it opens in libre office correctly.

1

There are 1 answers

0
Richard Muvirimi On

This is mainly due to the parser you are using not being able to process quoted and unquoted strings in the same line

to circumvent this you can use the csv parser that comes with PHP from https://www.php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c = 0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

You can paste this in a separate file, create a csv with name test.csv and your content