Mintz
Mintz

Reputation: 969

PHP: Read specific lines in a large file (without reading it line-by-line)

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

Upvotes: 4

Views: 8335

Answers (1)

Nimrod007
Nimrod007

Reputation: 9913

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

Upvotes: 16

Related Questions