4

我有这个文件结构:

line1 (number or a a short string)
line2 (can be several MB of text)
;
line1
line2
;
line1
line2
;
...

总文件大小超过 100MB,因此每次逐行读取它相当慢。我只想读取每个块的“line1”并跳过所有“line2”。或者只是阅读我知道行号的一行。有什么办法可以用php做到吗?读取行的标准方法将行放入内存,并且这种结构不太有效。

(我知道数据库结构会更好用,但这是一个我真的想要解决方案的研究案例。)

4

1 回答 1

16

使用 splfileobject

  • 无需逐行阅读所有行

  • 可以“跳转”到所需的行

如果您知道行号:

//lets say you need line 4
$myLine = 4 ; 
$file = new SplFileObject('bigFile.txt');
//this is zero based so need to subtract 1
$file->seek($myLine-1);
//now print the line
echo $file->current();

退房: http ://www.php.net/manual/en/splfileobject.seek.php

于 2013-10-14T11:15:05.367 回答