|
Read the last few rows 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 rows
* @ Return mixed false indicates an error occurred. If the request succeeds, a string is returned.
*/
Function FileLastLines ($ filename, $ n ){
If (! $ Fp = fopen ($ filename, 'R ')){
Echo "failed to open the file. Please check whether the file path is correct and 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 line of the file * @ param string $ filename file path * @ param int $ n the last few lines * @ return mixed false indicates an error occurred, returns the string */function FileLastLines ($ filename, $ n) {if (! $ Fp = fopen ($ filename, 'R') {echo "failed to open the file. Please check whether the file path is correct and 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 ));
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 |