PHP:读取大文件中的特定行(不需要逐行读取) [英] PHP: Read specific lines in a large file (without reading it line-by-line)
问题描述
line1(数字或一个简短字符串)
line2(可以是几个MB文字)
;
line1
line2
;
line1
line2
;
...
总文件大小超过了100MB,所以每次只读一行是相当缓慢的。
我只想读取每个块的line1,并跳过所有的line2。或者只是读一条线,我知道的linenumber。有什么办法,我可以做到这一点与PHP?读取行的标准方法是将行写入内存中,并且对于这种结构不是那么有效。
(我知道一个数据库结构会更好用,但这是)
使用splfileobject
-
不需要逐行读取所有行
/ p>
如果您知道行号:
//可以说你需要第4行
$ myLine = 4;
$ file = new SplFileObject('bigFile.txt');
//这是基于零的,所以需要减去1
$ file-> seek($ myLine-1);
//现在打印
echo $ file-> current();
检查:
http://www.php.net/manual/en/splfileobject.seek.php
I have this file structure:
line1 (number or a a short string)
line2 (can be several MB of text)
;
line1
line2
;
line1
line2
;
...
The total filesize is exceeding 100MB so reading it line by line each time is rather slow. I want to read only "line1" of each block and skip all the "line2". Or just read a line which I know the linenumber for. Is there any way that I can do it with php? The standard methods of reading lines takes the lines into memory and it not so effective with this structure.
(I know a database structure would be a much better use but this is a study-case that I really want an solution to.)
Using splfileobject
no need to read all lines 1 by 1
can "jump" to desired line
In the case you know the line number :
//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();
check out : http://www.php.net/manual/en/splfileobject.seek.php
这篇关于PHP:读取大文件中的特定行(不需要逐行读取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!