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;
}