PHP 

Here we will see how to read last n lines from a file in PHP, where n could be replaced by your 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 and apply some business processing logic on this according to the application’s requirements. But sometimes you need to read a file in backward direction and you want 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.

You may also like to read how to read last n lines from a file using Java.

Prerequisites

Knowledge of PHP

Let’s move on to the code implementation of how to read last n lines from a file in PHP…

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 1. When you need to extract last few lines from a small file then you can use below solution.

<?php

	$file = file("Terms and Conditions 2012_FRL.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.

Solution 2. This solution will work for your small as well as very big file. We 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('Terms and Conditions 2012_FRL.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));
	
?>

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.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *