tags:

views:

285

answers:

4

The closest I've seen in the PHP docs, is to fread() a given length, but that doesnt specify which line to start from. Any other suggestions?

+4  A: 

You not going to be able to read starting from line X because lines can be of arbitrary length. So you will have to read from the start counting the number of lines read to get to line X. For example:

<?php
$f = fopen('sample.txt', 'r');
$lineNo = 0;
$startLine = 3;
$endLine = 6;
while ($line = fgets($f)) {
    $lineNo++;
    if ($lineNo >= $startLine) {
        echo $line;
    }
    if ($lineNo == $endLine) {
        break;
    }
}
fclose($f);
grom
Or you could just use file() and array_slice(), as in my answer :)
Factor Mystic
Yeah except that reads the whole file. This code only reads the minimum required.
grom
will that work even the file is so huge like the one i currently need to work on is 25MB?
lock
@lock, yes it should. The example I gave only ever has one line in memory. You can store the lines into an array as long as don't have too many. Having said that 25Mb is not huge compared to some log files I have had to process.
grom
A: 

If you're looking for lines then you can't use fread because that relies on a byte offset, not the number of line breaks. You actually have to read the file to find the line breaks, so a different function is more appropriate. fgets will read the file line-by-line. Throw that in a loop and capture only the lines you want.

Andrew Vit
+2  A: 

Unfortunately, in order to be able to read from line x to line y, you'd need to be able to detect line breaks... and you'd have to scan through the whole file. However, assuming you're not asking about this for performance reasons, you can get lines x to y with the following:

$x = 10; //inclusive start line
$y = 20; //inclusive end line
$lines = file('myfile.txt');
$my_important_lines = array_slice($lines, $x, $y);

See: array_slice

Factor Mystic
You should note that the array starts with 0 and line numbering usually starts with 1. So there should be a $x-1, $y-1 or remember $x=10 is *really* $x=11.
null
+2  A: 

Solution from related link below question:

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