PHP在阅读时跳过行 [英] PHP skip lines while reading

查看:66
本文介绍了PHP在阅读时跳过行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种从csv文件读取的快速方法,方法是先跳过多行,读取大约20行,然后停止读取.目前唯一的解决方案是使用fread,效率很低.

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.

推荐答案

滚动浏览符合特定CSV格式的CSV的唯一方法是调用解析器.最快的CSV解析器是内置的fgetcsv.因此,这将是所有可能的可靠方法中最快的:

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

使用方式:

$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.

这篇关于PHP在阅读时跳过行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆