What is the recommended method for reading the last X lines of a .txt file in PHP?
To read the last X lines of a .txt file in PHP, you can use the `SplFileObject` class along with `fseek` to navigate to the end of the file and then read backwards until you reach the desired number of lines. This method is efficient and does not require loading the entire file into memory.
$filename = 'example.txt';
$lines = 5; // Number of lines to read
$file = new SplFileObject($filename, 'r');
$file->seek(PHP_INT_MAX); // Move pointer to end of file
$lineCount = 0;
$linesArray = [];
while (!$file->eof() && $lineCount < $lines) {
$file->seek($file->key() - 1);
$linesArray[] = $file->current();
$lineCount++;
}
$linesArray = array_reverse($linesArray); // Reverse array to get lines in correct order
foreach ($linesArray as $line) {
echo $line;
}
Keywords
Related Questions
- What is the best way to handle form variables in PHP, considering that they are all treated as strings?
- What are some best practices for handling timestamp values in PHP to avoid incorrect date calculations?
- How can the output of a timer function in PHP be updated and displayed without causing a complete page refresh?