在PHP中读取文件的特定行

tin*_*nks 6 php file

我正在读取PHP中的文件.我需要阅读该文件的特定行.

我用过这段代码:

fseek($file_handle,$start);
while (!feof($file_handle)) 
{   
    ///Get and read the line of the file pointed at.
    $line = fgets($file_handle);
    $lineArray .= $line."LINE_SEPARATOR";

    processLine($lineArray, $linecount, $logger, $xmlReply);

    $counter++;
}
fclose($file_handle);
Run Code Online (Sandbox Code Playgroud)

但是我意识到fseek()需要的是字节数而不是行号.

PHP有其他函数将其指针基于行号吗?

或者我每次都必须从头开始读取文件,并有一个计数器,直到我读取所需的行号?

我正在寻找一种有效的算法,步进超过500-1000 Kb文件到达所需的线似乎效率低下.

JRL*_*JRL 14

使用 SplFileObject::seek

$file = new SplFileObject('yourfile.txt');
$file->seek(123); // seek to line 124 (0-based)
Run Code Online (Sandbox Code Playgroud)


ale*_*ale 9

这对你有用吗?

$file = "name-of-my-file.txt";
$lines = file( $file ); 
echo $lines[67]; // echos line 68 (lines numbers start at 0 (replace 68 with whatever))
Run Code Online (Sandbox Code Playgroud)

显然,您需要在打印前检查线条是否存在.好不好?


Sud*_*oti 5

你可以这样做:

$lines = file($filename); //file in to an array
echo $lines[1];           //line 2
Run Code Online (Sandbox Code Playgroud)

或者

$line = 0;
$fh = fopen($myFile, 'r');

while (($buffer = fgets($fh)) !== FALSE) {
   if ($line == 1) {
       // $buffer is the second line.
       break;
   }   
   $line++;
}
Run Code Online (Sandbox Code Playgroud)