0

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

Community
  • 1
  • 1
sipher_z
  • 1,221
  • 7
  • 25
  • 48

1 Answers1

1

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.

Smar
  • 8,109
  • 3
  • 36
  • 48
  • Would I have to do that though for each field? – sipher_z Feb 07 '14 at 15:23
  • Do you have numerical indexes, or need to access with stuff like `$row["nya"]`? And do you know the indexes present, or do they change? – Smar Feb 07 '14 at 15:23
  • Doesn't `list()` create numerical index? – sipher_z Feb 07 '14 at 15:24
  • Also, how would I check inside the `list()` ? – sipher_z Feb 07 '14 at 15:27
  • No, `list()` is a function to automatically expand values from array. It takes first, second, and so on, elements from the array and puts them to variables you give. It’s shorthand for my way, but it does not do any checks whether the value really exists, so if more control is needed, it’s not suitable tool (I think I’ve used it like once or twice past two years) – Smar Feb 07 '14 at 15:27
  • Can you update your answer with a more detailed example, of how I could use it with my values? – sipher_z Feb 07 '14 at 15:29
  • Done. This assumes you use numerical indexes, if that’s not case, please answer to questions of my first comment and I’ll provide another example :) – Smar Feb 07 '14 at 15:33