Home > Article > Backend Development > Read last line of file in PHP
To read the last line of the file from PHP, the code is as follows -
$line = ''; $f = fopen('data.txt', 'r'); $cursor = -1; fseek($f, $cursor, SEEK_END); $char = fgetc($f); //Trim trailing newline characters in the file while ($char === "</p><p>" || $char === "\r") { fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "</p><p>" && $char !== "\r") { //Prepend the new character $line = $char . $line; fseek($f, $cursor--, SEEK_END); $char = fgetc($f); } echo $line;
The output will be the last line of the text file that is read and displayed.
The text file is opened in read mode with the cursor set to point to -1, i.e. initially there is no content. The 'fseek' function is used to move to the end of the file or the last line. The line is read until a newline character is encountered. After that, the read characters will be displayed.
The above is the detailed content of Read last line of file in PHP. For more information, please follow other related articles on the PHP Chinese website!