当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Reading a specific line from a text file

问题描述:

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.

网友答案:

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;

}
分享给朋友:
您可能感兴趣的文章:
随机阅读: