Zend Certified Engineer

phpguru.org

Free PHP, Javascript and C# code

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

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

The "new" way

<?php
    
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.

There is of course a downside. Unfortunately in a loop over a 23000 line file, the Iterator code proved to be roughly twice as slow as the "old" way, so using it in a speed critical situation isn't wise.

Download

References

On the subject of Iterators, you'll probably want to look at the following:

Link to me

If you use any of the code on this site (and if you don't I guess) or it makes your life easier, I'd appreciate a link - http://www.phpguru.org. Thanks!

Last modified: 16:30 29th December 2006