在PHP中读取文件的特定行 [英] Reading specific line of a file in PHP

查看:91
本文介绍了在PHP中读取文件的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用php读取文件. 我需要阅读文件的特定行.

I am working on reading a file in php. I need to read specific lines of the file.

我使用了以下代码:

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

但是我意识到fseek()接受字节数而不是行号.

However I realized that the fseek() takes the number of bytes and not the line number.

PHP是否还有其他基于行号的指针功能?

Does PHP have other function that bases its pointer in line numbers?

还是我必须每次都从头开始读取文件,并有一个 计数器,直到读完我想要的行号?

Or do I have to read the file from the start every time, and have a counter until my desired line number is read?

我正在寻找一种高效的算法,将500-1000 Kb的文件移至所需的行似乎效率低下.

I'm looking for an efficient algorithm, stepping over 500-1000 Kb file to get to the desired line seems inefficient.

推荐答案

使用 SplFileObject::seek

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

这篇关于在PHP中读取文件的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆