start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

18.9. Reading a Particular Line in a File

18.9.1. 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.

18.9.2. 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];

18.9.3. 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)) {

18.9.4. See Also

Documentation on fgets( ) at http://www.php.net/fgets and feof( ) at http://www.php.net/feof.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.