PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, May 17, 2022

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

 May 17, 2022     php     No comments   

Issue

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
}

Solution

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


Answered By - salathe
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing