PHP 5 FileIterator documentation
Requirements and Installation
These are the minimal requirements for installing and using the library.
- Any PHP5 version or greater
- 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();
}
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... [...]
Off 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();
}
More examples
More example usage can be found in the example page.
API Documentation
A full API Documentation for the package is available.
A full 
