RE: [PHP] including() only given amount of lines

From: Date: Sun, 11 May 2003 13:49:24 +0000
Subject: RE: [PHP] including() only given amount of lines
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-147201@lists.php.net to get a copy of this message
> From: iliketheworld@gmx.ch [mailto:iliketheworld@gmx.ch] > > >>>> 1. i would like to include only a given amount (the first > 50) lines of a > >>>> text file. i think they should be included using fgets() or fread() > >>>> instead of include() but i dont know how. > > >>> The easiest way would be to use file() and the array manipulation > >>> functions. > > >> yes, but isn't a 500+ line file a bit heavy to read into an array? i > >> thought this may cause massive slow down -- isn't it? > > > Assuming you have 500 lines each with 80 chars, that's around > 40KB. Further > > assume that in storing those lines into an array increases its storage > > requirements ten-fold. That still only uses 400KB -- a piddling > amount of > > memory these days (unless you're running your webserver on 32MB). > > > > For (1), if you wanted to do it using fgets() it's just a > simple matter of > > opening the file with fopen() then use a for-loop to call > fgets() 50 times. > > considering that my file contains more than 500 lines (and is > still growing) > with about 700 chars per line i just think that file() and an array is not > adequate and moreover unesthetic ;) > Assuming the box is *nix you can just use the 'head' shell function? $options = "-c 50"; // for first 50 bytes $options = "-n 50"; // for first 50 lines exec( "head "$options." ".$file, $out ); $out then has your lines.... as an array. > > currently i'm using this: > > $handle = fopen ($filename, "r"); > $i = 1; > while ($i <= 20) { > $buffer = fgets($handle, 4096); > echo $buffer; > $i++; > } > fclose ($handle); > man > but i also need to output a given amount of lines located somewhere in the > middle of the document: how can i print the lines from 130 to 150 for > example? > Ahh for this.... you'd better just use fopen as above and unset what you dont need. $handle = fopen ($filename, "r"); $i = 1; $want_from = 300; $want_to = 320; while ( true ) { $buffer = fgets($handle, 4096); if( $i > $want_to ) break; if( $i < $want_from ) { unset( $buffer ); } else { echo $buffer; } $i++; } fclose($handle)

« previous php.general (#147201) next »