需求如下:
现有一个1G左右的日志文件,大约有500多万行, 用php返回最后几行的内容。
实现方法:
function tail($fp,$n,$base=5)
{
assert($n>0);
$pos = $n+1;
$lines = array();
while(count($lines)<= $n){
try{
fseek($fp,-$pos,SEEK_END);
} catch (Exception $e){
fseek(0);
break;
}
$pos *= $base;
while(!feof($fp)){
array_unshift($lines,fgets($fp));
}
}
return array_slice($lines,0,$n);
}
$arr = tail(fopen("log.txt","r+"),100);
unset($arr[0]);
$lastTime = $nowtime;
foreach($arr as $v)
{
echo $v.'<br/>';
}