PHP - Returning the last line in a file?

后端 未结 9 1559
鱼传尺愫
鱼传尺愫 2020-11-30 09:46

I\'m guessing it\'s fgets, but I can\'t find the specific syntax. I\'m trying to read out (in a string I\'m thinking is easier) the last line added to a log file.

9条回答
  •  余生分开走
    2020-11-30 10:31

    ...Why just read the last line?

    function readLines($fp, $num) {
    
        $line_count = 0; $line = ''; $pos = -1; $lines = array(); $c = '';
    
        while($line_count < $num) {
            $line = $c . $line; 
            fseek($fp, $pos--, SEEK_END);
            $c = fgetc($fp);
            if($c == "\n") { $line_count++; $lines[] = $line; $line = ''; $c = ''; }
        }   
        return $lines;
    }
    
    $filename = "content.txt";
    $fp = @fopen($filename, "r");
    
    print_r(readLines($fp, 2));
    
    fclose($fp);
    

提交回复
热议问题