PHP - Returning the last line in a file?

后端 未结 9 1527
鱼传尺愫
鱼传尺愫 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:30

    define('YOUR_EOL', "\n");
    $fp = fopen('yourfile.txt', 'r');
    
    $pos = -1; $line = ''; $c = '';
    do {
        $line = $c . $line;
        fseek($fp, $pos--, SEEK_END);
        $c = fgetc($fp);
    } while ($c != YOUR_EOL);
    
    echo $line;
    
    fclose($fp);
    

    This is better, since it does not load the complete file into memory...

    Set YOUR_EOL to your correct line endings, if you use the same line endings as the default line endings of the OS where your script resides, you could use the constant PHP_EOL.

提交回复
热议问题