Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the extra line when using PHP SplFileObject and READ_CSV flag?

Tags:

php

When iterating over a csv file using PHP SplFileObject and the READ_CSV flag I get an extra row with a null value. Is there a way to remove this line automatically?

$file = new SplFileObject(__DIR__.'/technologies.csv', 'r');
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
    var_dump($row);
}

This will produce a row with a null value.

...
array(1) {
  [0] =>
  NULL
}
like image 641
Zorin Greene Avatar asked Sep 27 '15 08:09

Zorin Greene


1 Answers

You want to also set the SplFileObject::SKIP_EMPTY flag, and for that to work also the SplFileObject::READ_AHEAD flag.

The SplFileObject::SKIP_EMPTY flag does what it says on the tin: it skips empty lines. A trailing newline in your file counts as an empty line.

(Aside: SplFileObject::READ_AHEAD is needed so that SplFileObject::SKIP_EMPTY can do its job. The next line needs to be read, internally, so that PHP can determine if it is empty or not.)


So, your code will look like (wrapped on to multiple lines so you can read it):

$file->setFlags(SplFileObject::READ_CSV |
                SplFileObject::SKIP_EMPTY |
                SplFileObject::READ_AHEAD);
like image 65
salathe Avatar answered Nov 19 '22 23:11

salathe