当前位置:Gxlcms > PHP教程 > php获取文件的最后N行数据

php获取文件的最后N行数据

时间:2021-07-01 10:21:17 帮助过:2人阅读

本篇文章介绍的内容是php获取文件的最后N行数据,现在分享给大家,也可以给有需要的朋友一个参考

GitHub源码
代码是基于以下问题,给出的解决方案:
用php写一个函数,获取一个文本文件最后$n行内容,要求尽可能效率更高,并可以跨平台使用

我理解的可以跨平台使用,是说的文件在windows平台和linux平台的行结束符不一致问题,在代码中我们没有体现这种不同。全部是在linux系统下的代码。跨平台问题还需要理解?

  1. <?phpheader("content-type:text/html;charset=utf-8");class GetFileLastNumRow{
  2. private $filePath; private $fileMode = 'r'; private $rowNum = 3; public function __construct(array $config)
  3. {
  4. foreach ($config as $key => $value) { $this->$key = $value;
  5. }
  6. } public function run()
  7. {
  8. try { $handle = fopen($this->filePath, $this->fileMode);
  9. fseek($handle, -1, SEEK_END); $contents = ""; $rowCount = 0; do { if (($str = fgetc($handle)) == "\n") { $rowCount++;
  10. } $contents = $str.$contents;
  11. fseek($handle, -2, SEEK_CUR);
  12. } while ($rowCount < $this->rowNum);
  13. var_export(trim($contents, "\n"));
  14. fclose($handle);
  15. } catch(\Exception $e) {
  16. var_export($e->getMessage());
  17. }
  18. }
  19. }class Test{
  20. public function run()
  21. {
  22. $filePath = './TestData/GetFileLastNumRow/test.data'; $getFileLastNumRow = new GetFileLastNumRow(compact('filePath')); $getFileLastNumRow->run();
  23. }
  24. }$test = new Test();$test->run();

相关推荐:

PHP获取数组中指定一列的方法

PHP获取用户IP地址的方法

以上就是php获取文件的最后N行数据的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行