Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php ; using fgetcsv with SplFileObject::fseek ; line read issue

When reading a specific line in a csv file, I tried to use SplFileObject::fseek with fgetcsv.

To read line 2 (for example), I do a fseek(1) and read with fgetcsv, which gives line 2.

When I do a fseek(0) and read with fgetcsv, I have line 0.

So there is a issue to read line 1 this way. (I know I can read 2 lines in a row but don't think it is nice).

I found this issue reported in 2008 with PHP version 5.2.6 : SplFileObject: fgetcsv after seek returns wrong line.

I'm using PHP verion 5.4.19.

Has anyone some information on this? Is this intended?

like image 811
user2992220 Avatar asked Nov 10 '22 15:11

user2992220


1 Answers

I know this is a pretty old bug but it's still opened on bugs.php So here is a snippet I want to share to achieve the same (which at least work in my case)

function readBigCsv($path, $skip=1)
{
    $file = new \SplFileObject($path, 'r');
    $file->setFlags(\SplFileObject::READ_CSV);
    $file->seek($skip);

    while (!$file->eof()){
        yield $file->current();
        $file->next();
    }

}
like image 174
Sylwit Avatar answered Nov 15 '22 05:11

Sylwit