How to read only 5 last line of the text file in PHP?

前端 未结 18 1580
陌清茗
陌清茗 2020-11-28 08:45

I have a file named file.txt which is update by adding lines to it.

I am reading it by this code:

$fp = fopen(\"file.txt\", \"r\");
$da         


        
18条回答
  •  有刺的猬
    2020-11-28 09:32

    function ReadFromEndByLine($filename,$lines)
    {
    
            /* freely customisable number of lines read per time*/
            $bufferlength = 5000;
    
            $handle = @fopen($filename, "r");
            if (!$handle) {
                    echo "Error: can't find or open $filename
    \n"; return -1; } /*get the file size with a trick*/ fseek($handle, 0, SEEK_END); $filesize = ftell($handle); /*don't want to get past the start-of-file*/ $position= - min($bufferlength,$filesize); while ($lines > 0) { if ($err=fseek($handle,$position,SEEK_END)) { /* should not happen but it's better if we check it*/ echo "Error $err: something went wrong
    \n"; fclose($handle); return $lines; } /* big read*/ $buffer = fread($handle,$bufferlength); /* small split*/ $tmp = explode("\n",$buffer); /*previous read could have stored a partial line in $aliq*/ if ($aliq != "") { /*concatenate current last line with the piece left from the previous read*/ $tmp[count($tmp)-1].=$aliq; } /*drop first line because it may not be complete*/ $aliq = array_shift($tmp); $read = count($tmp); if ( $read >= $lines ) { /*have read too much!*/ $tmp2 = array_slice($tmp,$read-$n); /* merge it with the array which will be returned by the function*/ $lines = array_merge($tmp2,$lines); /* break the cycle*/ $lines = 0; } elseif (-$position >= $filesize) { /* haven't read enough but arrived at the start of file*/ //get back $aliq which contains the very first line of the file $lines = array_merge($aliq,$tmp,$lines); //force it to stop reading $lines = 0; } else { /*continue reading...*/ //add the freshly grabbed lines on top of the others $lines = array_merge($tmp,$lines); $lines -= $read; //next time we want to read another block $position -= $bufferlength; //don't want to get past the start of file $position = max($position, -$filesize); } } fclose($handle); return $lines; }

    This will be fast for larger files but alot of code for a simple task, if there LARGE FILES, use this

    ReadFromEndByLine('myFile.txt',6);

提交回复
热议问题