PHP 5 FileIterator example usage
Basic usage
The following is a basic usage sample. It reads a text file with FileIterator and displays row data.
<?php
$file = new FileIterator('file.txt');
foreach ($file as $line) {
echo $line . "<br />";
}
Basic usage (with exception)
The following is an improvement of the first basic usage example.
If input file cannot be read or something bad happens, FileIterator() throws a PHP5 exception. Catching it will give more control to the developer.
<?php
try {
// try to open the file
$file = new FileIterator('file.txt');
// and play with the content
foreach ($file as $ii => $line) {
// encode HTML entities
echo "$ii. " . htmlentities($line) . "<br />";
}
// end of file
echo str_repeat("=", 10) . " end of file " . str_repeat("=", 10);
}
catch(Exception $e) {
// display Exception message
echo "Error: " $e->getMessage();
}
An output example looks like this:
1. this is the first line of the file 2. and this is the second one with <HTML> entities encoded 3. more ouput [...] ========== end of file ==========
Advanced usage: isEmpty()
FileIterator::isEmpty($whitespaceAsChar) is one of the additional methods provided by this library.
It tests whether current row is empty. If $whitespaceAsChar is true (default), white spaces will be considered a valid char and the row not empty, otherwise a string with only spaces will be considered as empty.
<?php
try {
$file = new FileIterator('file.txt');
foreach ($file as $line) {
// print only not empty rows
if (!$file->isEmpty()) echo "line " . $file->key() ". " . htmlentities($file->current());
}
}
catch(Exception $e) {
echo "Error: " $e->getMessage();
}
Advanced usage: match()
FileIterator::match($whitespaceAsChar, $matches) returns true if current row matches given regular expression pattern.
For instance, suppose you need to find only rows that contain the word Apache or IIS.
If $matches is provided, then it is filled with the results of search.
<?php
try {
$file = new FileIterator('file.txt');
foreach ($file as $line) {
// print only row that contain Apache/IIS
if (!$file->match('/(Apache|IIS)/')) echo "line " . $file->key() ". " . htmlentities($file->current());
}
}
catch(Exception $e) {
echo "Error: " $e->getMessage();
}
A full 
