Zorin Greene
Zorin Greene

Reputation: 197

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

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
}

Upvotes: 6

Views: 3033

Answers (2)

Richard
Richard

Reputation: 541

I am using PHP 8.0.18 & I had to add one more flag in order to skip the empty lines, ie SplFileObject::DROP_NEW_LINE. The final code looks like;

$file->setFlags(
            SplFileObject::READ_CSV |
            SplFileObject::SKIP_EMPTY |
            SplFileObject::DROP_NEW_LINE |
            SplFileObject::READ_AHEAD
        );

Upvotes: 3

salathe
salathe

Reputation: 51950

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);

Upvotes: 12

Related Questions