仅显示 txt 文件中的最后 5 行


Show only the 5 last lines from a txt file

我想使用始终更新的文件url.txt,其中最新数据始终添加到文件底部。

我使用了这个脚本:

$file = fopen("url.txt","r");
while(! feof($file)){
  echo fgets($file). "<br />"; 
}
fclose($file);   

我只能读取文件中的所有内容。但我只是想获取最后 5 行并将它们显示在网络上。

您可以使用

此脚本

$f=file("url.txt");
$last=array_slice($f, -5);
echo implode("<br>",$last);

如果你想分析一个真正的大文件,你可以使用 shell 命令只获取一个单独的文件中最新的 5 行,如下所示:

shell_exec("tail -n 5 url.txt > /tmp/phptail_file");
echo nl2br(file_get_contents("/tmp/phptail_file"));

您可以访问数组,然后显示它。

$file = fopen("url.txt","r");
$data = array();
while(! feof($file))
      $data[] = fgets($file); 
fclose($file);
$count = count($data);
for($i = 4; $i <= 0; $i--)
      echo $data[$count - $i] . "<br>";