5

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?

Krish R
  • 22,583
  • 7
  • 50
  • 59
user2992220
  • 1,092
  • 1
  • 12
  • 20
  • Better to link to the PHP bug site: https://bugs.php.net/bug.php?id=46569 – Barmar Dec 31 '13 at 09:12
  • They haven't closed the bug report, so I don't think it's intended. They just haven't gotten around to fixing it yet. – Barmar Dec 31 '13 at 09:14

1 Answers1

1

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

}
Sylwit
  • 1,497
  • 1
  • 11
  • 20