Skip to content

Documentation

weppos edited this page Jan 30, 2011 · 3 revisions

Documentation

Requirements and Installation

Below are the minimum requirements you needs to use the library.

  1. Any PHP 5 version or greater
  2. PHP’s PCRE (Perl Compatible Regular Expressions) support

The class doesn’t require any installation.
Simply download it from this website, decompress the archive then move the FileIterator.php library to the proper location, for instance your website PHP library folder.

Getting Started

Starting with FileIterator is really simple.
First of all you need to include the library in order to create a new FileIterator() instance.

The following statement supposes that the library is within the same folder of the file that includes it.

require_once 'FileIterator.php';

Now you can safely create a new FileIterator() instance calling FileIterator constructor.
FileIterator() requires a valid $source file as argument. You can change file source path later on your code, but you can’t create a new instance without a file path.

try {
  $file = new FileIterator('path/to/file.txt');
}
catch(Exception $e) {
  echo "An error occurred: " . $e->getMessage();
}

Invalid file source exception

FileIterator constructor tries to read the file as soon as a new instance is created.
If source file can’t be read, the constructor throws an Exception.

You are encouraged to handle all possible exceptions with a try an catch block.

Note. The exception is thrown by FileIterator::_openPointer() private method, called by FileIterator constructor.

Great! Now $file holds a new FileIterator instance.
You can loop over the Iterator to read all file rows. You would probably use foreach() statement, which is used to make easy work of looping through an array.
As a matter of fact, an Iterator object is very similar to an array and provides basic methods such as next(), rewind(), key(), current() and valid().


foreach ($file as $ii => $line) {
  echo "line $ii. " . $line . "";
}

The code above will print out something like this:

line 1. this is the first line
line 2. and now the second one
line 3. and now more data...
[...]

Of course, you can use while statement as well. Let’s have a look to this example.

$nofLines = 5; // fetch only first 5 lines
while ($file->valid() && $file->key() < $nofLines) {
  echo sprintf("line %s. %s <br />", 
               $file->key() + 1, 
               $file->current());
  $file->next();
}

$file→next()

If you while() statement don’t forget to move the file pointer to the next row calling FileIterator::next() method.

Examples

For more examples visit the examples page.

Clone this wiki locally