18.8. Reading a Particular Line in a File
Problem
You want to read a specific line in a file; for example, you want to read the most recent guestbook entry that’s been added on to the end of a guestbook file.
Solution
If the file fits into memory, read the file into an array and then select the appropriate array element:
$lines = file('vacation-hotspots.txt'); print $lines[2];
Discussion
Because array indexes start at 0, $lines[2]
refers
to the third line of the file.
If the file is too big to read into an array, read it line by line and keep track of which line you’re on:
$line_counter = 0; $desired_line = 29; $fh = fopen('vacation-hotspots.txt','r') or die($php_errormsg); while ((! feof($fh)) && ($line_counter <= $desired_line)) { if ($s = fgets($fh,1048576)) { $line_counter++; } } fclose($fh) or die($php_errormsg); print $s;
Setting $desired_line
=
29
prints the 30th line of the file, to be
consistent with the code in the Solution. To print the 29th line of
the file, change the while
loop line to:
while ((! feof($fh)) && ($line_counter < $desired_line)) {
See Also
Documentation on fgets( )
at
http://www.php.net/fgets and feof( )
at http://www.php.net/feof.
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.