3

Possible Duplicate:
Getting one line in a huge file with PHP

I have a file text with something like 200 lines and I want to read a specific line from this text file. how can I do it?

Thank you.

Community
  • 1
  • 1
Luis
  • 3,257
  • 13
  • 50
  • 59

3 Answers3

2

I am sure this is a duplicate, but anyway:

$file = new SplFileObject('file.txt');
$file->seek($lineNumber); // zero based
echo $file->current();

marking CW because middaparka found the duplicate

Gordon
  • 312,688
  • 75
  • 539
  • 559
2

Untested.

function getline($file, $linenum, $linelen = 8192) {
    $handle = fopen($file, "r");

    if ($handle) {
        while (!feof($handle)) {
            $linenum -= 1;
            $buffer = fgets($handle, $linelen); // Read a line.
            if (!$linenum) return $buffer;
        }
        fclose($handle); // Close the file.
    }

    return -1;
}
orlp
  • 112,504
  • 36
  • 218
  • 315
  • 1
    Suppressing errors on an fopen and then presuming all is well - classy. (Also love to know what the quotes are for around the "$file" on the fopen line.) – John Parker Jan 17 '11 at 22:00
  • Ahh woops, the quote and @ were an error because I copypasted the basecode from somewhere :) – orlp Jan 17 '11 at 22:02
0

Something like this would do it - keep reading lines from a file until you get the one you want (the last line makes sure we return false if we didn't find the line we wanted.

function getLine($file, $lineno)
{
    $line=false;
    $fp=fopen($file, 'r');
    while (!feof($fp) && $lineno--)
    {
        $line=fgets($fp);
    }
    fclose($file);
    return ($lineno==0)?$line:false;

}
Paul Dixon
  • 295,876
  • 54
  • 310
  • 348