weppos edited this page Jan 30, 2011 · 2 revisions
Clone this wiki locally

PHP5 FileIterator

FileIterator is a PHP 5 open source class, implementing PHP Interator interface. It provides an object oriented class for reading and parsing text files.

Iterator interface comes from the new SPL (Standard PHP Library), a collection of interfaces and classes that are meant to solve standard problems.
The goal of Iterator interface is to “provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure” (via SitePoint).

PHP 4 vs PHP 5 (iterator) way

Let’s have a look at the traditional, old-fashioned, PHP 4 script to open a file.

$fp = fopen( 'file.txt', 'r' ) ;
if ($fp) {
  while (!feof($fp)) {
    $line = fgets($fp, 4096);
    // $line holds row data

Obviously the same code could be rewritten using file() or file_get_contents(), but have a look at this PHP 5 brand new coding style!

$file = new FileIterator('file.txt');
foreach ($file as $line) {
  // $line holds row data

FileIterator makes file management easier than ever!

Are you surprised? Take a minute to look all FileIterator additional methods such as match() or isEmpty() and discover how it’s easy to read and manage a text file.


View the Documentation page for more details and don’t forget to check out the available Examples.


FileIterator is available under the GNU Lesser General Public License.