本篇文章介绍的内容是php获取文件的最后N行数据,现在分享给大家,也可以给有需要的朋友一个参考
GitHub源码
代码是基于以下问题,给出的解决方案:
用php写一个函数,获取一个文本文件最后$n行内容,要求尽可能效率更高,并可以跨平台使用
我理解的可以跨平台使用,是说的文件在windows平台和linux平台的行结束符不一致问题,在代码中我们没有体现这种不同。全部是在linux系统下的代码。跨平台问题还需要理解?
<?phpheader("content-type:text/html;charset=utf-8");class GetFileLastNumRow{
private $filePath; private $fileMode = 'r'; private $rowNum = 3; public function __construct(array $config)
{
foreach ($config as $key => $value) { $this->$key = $value;
}
} public function run()
{
try { $handle = fopen($this->filePath, $this->fileMode);
fseek($handle, -1, SEEK_END); $contents = ""; $rowCount = 0; do { if (($str = fgetc($handle)) == "\n") { $rowCount++;
} $contents = $str.$contents;
fseek($handle, -2, SEEK_CUR);
} while ($rowCount < $this->rowNum);
var_export(trim($contents, "\n"));
fclose($handle);
} catch(\Exception $e) {
var_export($e->getMessage());
}
}
}class Test{
public function run()
{
$filePath = './TestData/GetFileLastNumRow/test.data'; $getFileLastNumRow = new GetFileLastNumRow(compact('filePath')); $getFileLastNumRow->run();
}
}$test = new Test();$test->run();相关推荐:
以上就是php获取文件的最后N行数据的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号