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.
References
On the subject of Iterators, you'll probably want to look at the following:
-
http://www.php.net/spl
SPL (Standard PHP Library) documentation in the PHP manual. This is a collection of Iterator classes which tackle common problems.
-
http://www.php.net/~helly/php/ext/spl/
doxygen documentation for SPL. (Similar sort of thing to PHPDoc).
-
http://www.sitepoint.com/article/php5-standard-library/1
An article by Harry Fuecks about SPL, with a neat idea for HTML_TreeMenu.