Saturday, June 5, 2010

FileIterator


FileIterator

A truly superb addition to PHP5 was the ability for a foreach() loop to loop over objects in a user definable way, assuming they implement the Iterator interface. This means you can create custom objects that handle a common loop operation, and use foreach() to perform the loop in your code.
The FileIterator class takes advantage of this to enable you to very easily loop over each line of a file, without having to write the same code over and over again. If that didn't mean much to you, have a look at this...

The "old" way

    $fp fopen('myFile.txt''rb');
  
    if (
$fp) {
        while (!
feof($fp)) {
            
$line fgets($fp1024);
          
            
// Do stuff with $line...
        
}
    }
?>

The "new" way

    foreach (new FileIterator('myFile.txt') as $line) {
        
// Do stuff with $line...
    
}?>
How goddamn sexy is that? FYI, you can if you wish specify a read buffer size to the constructor, which the calls to fgets() will use.

No comments:

Post a Comment