How to read last n lines from a file in PHP

Introduction

Here we will see how to read last n lines from a file in PHP, where n could be replaced by any positive integer number, such as, 1, 2, 5, 10 etc. Generally most of the times we use to read the file in forward direction, i.e., from the beginning of the file and apply some business processing logic on file data according to the application’s requirements.

Sometimes you need to read a file in backward direction, i.e., from the end of the file and you may need to extract last few lines from a file for your application’s need. Then you can use one of the solutions from below code snippets.

I am going to use text file in this example. The sample file can be downloaded later from the source code link given at the bottom of this tutorial.

Related Posts:

Prerequisites

Apache HTTP Server 2.4, PHP 7.4.3

Project Directory

It’s assumed that you have setup Apache and PHP in Windows system.

Now I will create a project root directory called php-file-read-last-n-lines under the Apache server’s htdocs folder.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

Read Last n Lines

Your file may be a small, medium or big depending on your project’s requirements and here I will present with two different solutions you can use according to your need.

Solution – One

When you need to extract last few lines from a small file then you can use below solution.

The sample file license.txt is available in the source code link.

<?php

	$file = file("license.txt");
	$readLines = max(0, count($file) - n); //n being non-zero positive integer

	if($readLines > 0) {
		for ($i = $readLines; $i < count($file); $i++) {
			echo $file[$i];
			echo nl2br("\n");
		}
	} else {
		echo 'file does not have required no. of lines to read';
	}

?>

The above solution will consume much memory, so if your file is small then only use the above solution.

Executing the above code will give you the following output assuming n=10:

 read last n lines from a file in php

Solution – Two

This solution will work for your small as well as very big file. I will use here SplFileObject to reduce the memory cost. Use the seek() method to fetch the last line. You should then subtract the current key value by n, where n being the non-zero positive integer.

<?php	
	$file = new SplFileObject('license.txt', 'r');
	$file->seek(PHP_INT_MAX);
	$last_line = $file->key();
	$lines = new LimitIterator($file, $last_line - n, $last_line); //n being non-zero positive integer
	print_r(iterator_to_array($lines));
	
	// Iterate each element
	/*$it = iterator_to_array($lines);
	
	foreach($it as $ele){
		echo nl2br($ele . "\n");
	}*/
?>

Executing the above code will give you the following output assuming n=10:

 read last n lines from a file in php

Note that SplFileObject class has a private property that holds the file pointer. Therefore, there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink() method, because an SplFileObject still has a handle open. Then you have to do some workaround in the following way to delete the file.

$file = new SplFileObject("filename.txt");
$file = null; //explicitly assign null
unlink($file); //now delete the file

That’s all. Hope you got idea how to read last n lines from a file in PHP.

Source Code

Download

Thanks for reading.

Related posts

Leave a Comment