How to read every last two lines in file?

Hi, How would i read the last two line in text file,

Thank you in advance.

I’m new to PHP, so I’m sure there is a much more elegant solution that this However the script below works for me, when file.txt is the text file you want to read the last two lines from.

<?php
	
	$file = "./file.txt";
	$num_lines = 0;
	$fp = fopen($file, "r");
	
	while(!feof($fp)) {
		$line = fgets($fp, 1024);
		$num_lines++;
	}  // while
	
	define("TOTAL_LINES", $num_lines);
	$num_lines = 0;
	fclose($fp);
	
	$fp = fopen($file, "r");
	while(!feof($fp)) {
		$line = fgets($fp, 1024);
		$num_lines++;
		if($num_lines == (TOTAL_LINES-1) || $num_lines == TOTAL_LINES) {
			echo $line . "<br />";
		}  // if
	}  // while

	fclose($fp);
	
	?>

He felgal Thank you it’s working :slight_smile:

What about last line ??

Thank you in advance.

You’re welcome jemz. The version below will output the last line only;

<?php
	
	$file = "./file.txt";
	$num_lines = 0;
	$fp = fopen($file, "r");
	
	while(!feof($fp)) {
		$line = fgets($fp, 1024);
		$num_lines++;
	}  // while
	
	define("TOTAL_LINES", $num_lines);
	$num_lines = 0;
	fclose($fp);
	
	$fp = fopen($file, "r");
	while(!feof($fp)) {
		$line = fgets($fp, 1024);
		$num_lines++;
		if($num_lines == TOTAL_LINES) {
			echo $line . "<br />";
		}  // if
	}  // while

	fclose($fp);
	
	?>

Thank you so much it works again. :slight_smile:

Hi jemz,

This will output the last line of a file:

$lines = file('test.txt');
$lastLine = array_pop($lines);
echo $lastLine;

but will load the whole file into memory, which for a multi-megabyte log file, probably isn’t what you want.

If you are on a Linux/Unix box, this is a nicer way:

echo system('tail -n 1 test.txt');

See also: http://stackoverflow.com/questions/1510141/read-last-line-from-file

Thank you Pullo :slight_smile:

Thanks Pullo, I knew someone would have a more elegant solution than mine, but I wasn’t expecting it to be quite so elegant :slight_smile:

I’m assuming that happens, when you create the array with file() ?

Thanks :slight_smile:

Yup. That’s right.
The file() function reads an entire file into an array, which is allocated memory accordingly.