|
Read the last few lines of data from a large file:
/**
* The last $n row of the file
* @param string $filename file path
* @param int $n last few lines
& nbsp;* @return Mixed False indicates an error, and success returns the string
*/
Function Filelastlines ($filename, $n) {
if (! $fp =fopen ($filename, ' R ')} {
echo has failed to open the file, please check that the file path is correct. Path and filename do not contain Chinese ";
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));
/** * Fetch file last $n line * @param string $filename file path * @param int $n Last lines * @return Mixed false indicates an error , success returns the string /function Filelastlines ($filename, $n) { if (! $fp =fopen ($filename, ' R ')) { echo "Open file failed, please check file path is correct, path and filename do not include Chinese"; 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));
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
|