-
Notifications
You must be signed in to change notification settings - Fork 3
examples
weppos edited this page Jan 30, 2011
·
2 revisions
The following is a basic usage sample. It reads a text file with FileIterator and displays row data.
$file = new FileIterator('file.txt');
foreach ($file as $line) {
echo $line . "<br />";
}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.
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();
}
</code></pre>
A sample output looks like the following one:
<pre>
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 ==========
</pre>
h2. 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();
}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.
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();
}