Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

file-io

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

like image 882
Mintz Avatar asked Dec 05 '22 09:12

Mintz


1 Answers

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

like image 133
Nimrod007 Avatar answered Feb 03 '23 11:02

Nimrod007