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

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

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

This will result in a null string.

 ... array(1) { [0] => NULL } 
+5
source share
1 answer

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

The flag SplFileObject::SKIP_EMPTY does what it says in the sheet: it skips empty lines. The end line of a new line in your file is considered an empty line.

(Beyond: SplFileObject::READ_AHEAD requires 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 (wrapped over several lines so you can read it):

 $file->setFlags(SplFileObject::READ_CSV | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD); 
+6
source

Source: https://habr.com/ru/post/1232388/


All Articles