用PHP显示文件的最后5行?

时间:2015-01-03 00:07:30

标签: php

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

line1
line2
line3
line4
line5
line6
line7
line8
line9
line10

我希望输出如下:

line5
line6
line7
line8
line9
line10

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

5 个答案:

答案 0 :(得分:2)

$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;

答案 1 :(得分:1)

&#34;这是我之前准备的一个&#34;

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

答案 2 :(得分:0)

<强>解决

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

答案 3 :(得分:0)

不像使用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()开销

答案 4 :(得分:0)

$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