Read the last few lines of data from a large file:
/**
* Get the last $n lines of the file
* @param string $filename file path
* @param int $n the last few lines
* @return mixed false indicates an error, and if successful, returns a string
*/
function FileLastLines($filename,$n){
If(!$fp=fopen($filename,’r')){
echo "Failed to open the file, please check whether the file path is correct. The path and file name do not contain Chinese characters";
return false;
}
$pos=-2;
$eof=””;
$str=””;
While($n>0){
while($eof!=”n”){
If(!fseek($fp,$pos,SEEK_END)){
$eof=fgetc($fp);
$pos–;
}else{
break;
}
}
$str.=fgets($fp);
$eof=””;
$n–;
}
Return $str;
}
echo nl2br(FileLastLines(‘sss.txt’,4));
/*** Get the last $n lines of the file * @param string $filename file path * @param int $n The last few lines * @return mixed false means there is an error, and return a string if successful*/ function FileLastLines($filename,$n){ if(!$fp=fopen($filename,'r')){ echo "Failed to open the file, please check whether the file path is correct, the path and The file name should not contain Chinese characters "; " !fseek($fp,$pos,SEEK_END)){ $str.=fgets($fp); $n--; } } return $str; } echo nl2br(FileLastLines('sss.txt',4));
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);
}
var_dump(tail(fopen("access.log","r+"),10));
$fp = fopen($file, "r");
$line = 10;
$pos = -2;
$t = " ";
$data = "";
while ($line > 0) {
while ($t != "n") {
fseek($fp, $pos, SEEK_END);
$t = fgetc($fp);
$pos --;
}
$t = " ";
$data .= fgets($fp);
$line --;
}
fclose ($fp);
echo $data
|