Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to find a quick way of reading from a csv file, by first skipping a number of lines, reading about 20 lines, then stopping the read. the only solution right now is using fread, which is pretty inefficient.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

The only way to scroll through a CSV that respects the particular CSV format is to invoke a parser. The fastest CSV parser is the built in fgetcsv. Thus, that's going to be fastest of all possible reliable methods:

function csv_slice($fp, $offset = 0, $length = 0) {
    $i = 0;
    while (false !== ($row = fgetcsv($fp))) {
        if ($i++ < $offset) continue;
        if (0 < $length && $length <= ($i - $offset - 1)) break;
        yield $row;
    }
}

Used like:

$fp = fopen('file.csv', 'r');
print_r(
    iterator_to_array(
        csv_slice($fp, 5, 2) // start after 5th row, return 2 rows
    )
);
fclose($fp);

I've used generators here to keep the memory consumption low. You can easily replace with a temporary array if you prefer.

If you can make some assumptions about line endings, then you can just read byte-by-byte until you found the range of line endings. But, frankly, I wouldn't do that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...