Question

I'm parsing a large CSV file using SplFileObject. This CSV has almost 100,000 records and mutliple columns.

Some of these columns are empty.

I have the following code:

$file = new SplFileObject($uploadedFile);

$file->setFlags(SplFileObject::READ_CSV);

// ignore the header
$it = new LimitIterator($file, 1);

foreach ($it as $row) {
    list(
        $email,
        $name) = $row;
}

When I run the script, I always get an error:

PHP Notice: Undefined offset: 1 in script.php on line 5

PHP Notice: Undefined offset: 2 in script.php on line 5

    ............

PHP Notice: Undefined offset: 35 in script.php on line 5

Line 5 is the actual list() = $row

Is there a way I can fix this? Maybe by checking that the array has values?

Thanks

Was it helpful?

Solution

I’d do this by manually checking if the data exists, by

foreach ($it as $row) {
    if(isset($row[0])) {
        $email = $row[0];
    } else {
        // if you want to handle case where email is not present, just do something here
    }
    if(isset($row[1])) {
       $name = $row[1];
    }

    // now here you have $email and $name set to values from the array.
}

for example, if you have numerical indexes.

This would give you stricter control over the format of what will be parsed and in case of problems, faster to debug where exactly a value is missing or otherwise follow the logic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top