NYCPHP Meetup

NYPHP.org

[nycphp-talk] Reading just a couple lines of a file?

csnyder chsnyder at gmail.com
Wed Mar 26 11:51:40 EDT 2008


On 3/26/08, Ben Sgro <ben at projectskyline.com> wrote:
>
>  Hello,
>
>  Performance: Yeah, you don't have to hold the entire file in memory. Use
>  fopen/fread and iterate through
>  with a buffer size.
>
>
>  - Ben

And since you're searching for something specific, you can even just
go line by line using fgets() till you find what you want:

$fp = fopen( $file, r );
while( !feof($fp) ) {
  $line = fgets( $fp );
  if ( strpos( $line, '<title' ) !== FALSE ) {
    break;
  }
}
if ( !feof( $fp ) ) {
  // get title out of $line here
}

Since you're working with big files, it makes sense to build a better
limit into the while loop, to bail out if the title isn't found after
99 lines or something.

-- 
Chris Snyder
http://chxo.com/



More information about the talk mailing list