6.18 Extracting a Single Line from a File


You want to read a particular line in a file.

Technique

The quickest (as far as programming time is concerned ) solution is to load the file into an array of lines and specify which line you want:

 <?php $f_contents = file ($fn); $your_line = $f_contents[$line_num]; ?> 

Or you can loop through the file until you reach the desired line number:

 <? $line_cnt = 0; while ($line = fgets($fp, 1024)) {     if ($line_cnt == $line_num) {         $right_line = $line;         break;     }     $line_cnt++; } ?> 

Comments

The second solution is faster and more memory efficient; instead of reading the whole file into an array, we loop through the file until we reach the desired line number. With small files, you won't really see this speed increase, but as the files become larger, so does the speed increase.

The following program takes a filename and line number and returns the related line:

 getline.php #!/usr/bin/php <?php // PHP must be installed as a cgi for this to work list(, $file, $line_num) = array_values ($argv); $fp = fopen($file, "r"); $line_cnt = 0; while ($line = fgets($fp, 1024)) {     if ($line_cnt == $line_num) {         $what_we_want = $line;         break;     }     $line_cnt++; } if (isset($what_we_want))     print $what_we_want; ?> 

Running this at the command prompt (UNIX)

 % ./getline.php http://www.yahoo.com/ 59 

or the DOS prompt

 >php getline.php http://www.yahoo.com/ 59 

would fetch the 60th line on Yahoo!



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net