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

1.7k views Asked by At

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?

1

There are 1 answers

0
Sylwit On

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

}