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
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With