如何从第x行到第y行读取文件(使用php) [英] How to read a file from line x to line y (with php)

查看:109
本文介绍了如何从第x行到第y行读取文件(使用php)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在互联网上进行了探索,以找到解决方案;但他们都忽略了一个重要问题.最好的解决方案是在Stack Overflow中

I've explored all over the internet to find a solution; but all of them are neglecting an important issue. The best solution was in Stack Overflow as

  $file = new SplFileObject('longFile.txt');
    $fileIterator = new LimitIterator($file, 1000, 2000);
    foreach($fileIterator as $line) {
    echo $line, PHP_EOL;
    } 

但是,与其他方法一样,这需要从文件的开头读取以到达偏移量行.通常,它可以忽略不计;但是对于大文件(例如数百万行),这会大大减慢该过程.时间随着偏移量的增加而单调增加.如果您将偏移量设置为百万,则处理时间将为几秒钟.

But like other approaches, this needs to read from the beginning of the file to reach the offset line. Usually, it is negligible; but for large files (say millions of line), this significantly slow down the process. The time increases monotonically by the increase of the offset. If you put the offset at millions, the process time will be few seconds.

在数据库(如mysql)中,我们对表进行索引以读取一行,而无需遍历整个数据库.是否可以使用文件密钥(行号)执行此操作?我想知道像SQLite和Berkeley DB这样的平面文件数据库如何索引它们的表.

In databases (like mysql), we index the table to read a row without walking through the whole database. Is there to do such thing with the file key (line number)? I wonder how flat file databases like SQLite and Berkeley DB do index their tables.

推荐答案

此处的概念性问题是文件只是字符串,其中一些字符表示行尾.因此,如果不先读取文件,就无法知道行的开始和结束位置.

The conceptual problem here is that files are just strings of characters, some of those characters denote ends of lines. Because of that, it is impossible to know where lines begin and end without reading the file first.

如果要不断读取文件,请先扫描文件,然后将行的偏移量记录到某种索引中,然后使用 fread()即可准确读取所需的行.

If a file is to be read constantly, you scan the file first and record the offsets for the lines into some kind of index and use fseek() and fread() to read exactly the lines you want.

正如您提到的,数据库可以为您做类似的工作,而不是本质上创建您自己的数据库,您可以逐行读取文件,然后将这些行插入数据库中,其中某些字段存储行号然后通过查询获取所需的行.

As you mentioned, databases can do a similar job for you so, instead of creating, essentially, your own database, you could read the file line–by–line and insert those lines in database with some field storing the line number and then get the lines you want with a query.

这篇关于如何从第x行到第y行读取文件(使用php)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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