开发者

Reading a specific line from a text file [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Ge开发者_JAVA百科tting 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.


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;
}


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


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;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜