Skip to content

Instantly share code, notes, and snippets.

@nawawi
Created July 3, 2020 07:05
Show Gist options
  • Select an option

  • Save nawawi/2923d779b87d94bc033bf036dba8775c to your computer and use it in GitHub Desktop.

Select an option

Save nawawi/2923d779b87d94bc033bf036dba8775c to your computer and use it in GitHub Desktop.
<?php
// https://stackoverflow.com/a/41634468
$file = new SplFileObject("/path/to/file");
$file->seek(PHP_INT_MAX); // cheap trick to seek to EoF
$total_lines = $file->key(); // last line number
// output the last twenty lines
$reader = new LimitIterator($file, $total_lines - 20);
foreach ($reader as $line) {
echo $line; // includes newlines
}
// Or without the LimitIterator:
$file = new SplFileObject($filepath);
$file->seek(PHP_INT_MAX);
$total_lines = $file->key();
$file->seek($total_lines - 20);
while (!$file->eof()) {
echo $file->current();
$file->next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment