Read last line of file in PHP

WBOY
Release: 2023-08-27 22:10:01
forward
1732 people have browsed it

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;
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template