使用 PHP 仅显示文件的最后 5 行


Show only the last 5 lines of a file with PHP?

有没有办法用 PHP 只显示文件的最后 5 行? 例如,我有这个文件:

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10

我希望输出是这样的:

line5
line6
line7
line8
line9
line10

注意:这是一个日志文件,该行将继续,直到我的程序关闭

$text = "line1
line2
line3
line4
line5
line6
line7
line8
line9
line10";
$ex = explode("'n", $text);
$string = "";
for($i = count($ex) - 5; $i <= count($ex); $i++) {
 $string .= $ex[$i]."'n";
}
print $string;

"这是我之前准备的"

 $fh=popen("tail -5 ".escapeshellarg($filename),'r');
 echo read($fh);
 pclose($fh);

已解决

$file = file("/www/wget.log");
for ($i = count($file)-6; $i < count($file); $i++) {
  echo $file[$i] . "'n";
}

不像使用 file() 那样耗费内存

$fh = fopen($myFile, 'r');
$lines = array();
while (!feof($fh)) {
    $lines[] = fgets($fh, 999);
    if (count($lines) > 5) {
        array_shift($lines);
    }
}
fclose($fh);
foreach($lines as $line)
    echo $line;

以及(只是为了运气)使用 SPL 的相同逻辑的版本

$fh = new SPLFileObject($myFile);
$lines = new SPLQueue();
while (!$fh->eof()) {
    $lines->enqueue($fh->fgets());
    if (count($lines) > 5) {
        $lines->dequeue();
    }
}
while(!$lines->isempty())
    echo $lines->dequeue();
echo '---', PHP_EOL;

这可能(未经测试)比使用数组更快,因为它没有 array_shift() 开销

$lines=array();
$fp = fopen("file.txt", "r");
while(!feof($fp))
{
   $line = fgets($fp, 4096);
   array_push($lines, $line);
   if (count($lines)>5)
       array_shift($lines);
}
fclose($fp);

--

//how many lines?
$linecount=5;
//what's a typical line length?
$length=40;
//which file?
$file="test.txt";
//we double the offset factor on each iteration
//if our first guess at the file offset doesn't
//yield $linecount lines
$offset_factor=1;

$bytes=filesize($file);
$fp = fopen($file, "r") or die("Can't open $file");

$complete=false;
while (!$complete)
{
    //seek to a position close to end of file
    $offset = $linecount * $length * $offset_factor;
    fseek($fp, -$offset, SEEK_END);

    //we might seek mid-line, so read partial line
    //if our offset means we're reading the whole file, 
    //we don't skip...
    if ($offset<$bytes)
        fgets($fp);
    //read all following lines, store last x
    $lines=array();
    while(!feof($fp))
    {
        $line = fgets($fp);
        array_push($lines, $line);
        if (count($lines)>$linecount)
        {
            array_shift($lines);
            $complete=true;
        }
    }
    //if we read the whole file, we're done, even if we
    //don't have enough lines
    if ($offset>=$bytes)
        $complete=true;
    else
        $offset_factor*=2; //otherwise let's seek even further back
}
fclose($fp);
var_dump($lines);

来源: https://stackoverflow.com/a/2961685/3444315

和有用的样本:http://php.net/manual/en/function.fgets.php