如何在PHP中仅读取文本文件的最后5行? [英] How to read only 5 last line of the text file in PHP?

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

问题描述

我有一个名为file.txt的文件,该文件通过添加行来更新.

I have a file named file.txt which is update by adding lines to it.

我正在通过以下代码阅读它:

I am reading it by this code:

$fp = fopen("file.txt", "r");
$data = "";
while(!feof($fp))
{
$data .= fgets($fp, 4096);
}
echo $data;

,并且出现大量行. 我只想回显文件的最后5行

and a huge number of lines appears. I just want to echo the last 5 lines of the file

我该怎么做?

file.txt像这样:

11111111111111
22222222222

33333333333333
44444444444

55555555555555
66666666666

推荐答案

未经测试的代码,但应该可以:

Untested code, but should work:

$file = file("filename.txt");
for ($i = max(0, count($file)-6); $i < count($file); $i++) {
  echo $file[$i] . "\n";
}

调用max将处理少于6行的文件.

Calling max will handle the file being less than 6 lines.

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

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