Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LimitIterator offset 1 with 2 elements

Tags:

php

csv

The problem I'm facing is that I have a SplFileObject that reads a CSV file, then I wrap it into a LimitIterator.

The CSV file has 2 rows, header, and 1 row, I set the LimitIterator offset to 1 and I can't reach over it, seems some internal problems with the indexing.

here is the code:

    $csvFile = new \SplFileObject($fileName);
    $csvFile->setFlags(\SplFileObject::READ_CSV);
    $iterator = new \LimitIterator($csvFile, 1);

    /** @var \LimitIterator $it */
    foreach ($iterator as $it) {

        list($.., $.., $..) = $it;
        $result[] = [
            ...
        ];
    }


    return $result;

The code works well if the CSV has 3 lines (header and 2 rows), but only with header and 1 row, it doesn't work.

Any Idea?

Thanks.

like image 227
redigaffi Avatar asked Nov 18 '22 08:11

redigaffi


1 Answers

This is related to PHP bug 65601, which suggests adding the READ_AHEAD flag will fix this. Tested and works as you expected it to.

    $csvFile->setFlags(\SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD);

See also SplFileObject + LimitIterator + offset

like image 144
gaddman Avatar answered Feb 16 '23 13:02

gaddman