note 41636 modified in ref.spl by nlopess
| From: | nlopess@php.net | Date: | Sat, 17 Apr 2004 19:43:32 +0000 |
| Subject: | note 41636 modified in ref.spl by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-68259@lists.php.net to get a copy of this message | ||
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple
treeview of a given directory:
<?php
function recurse($it) {
echo '<ul>';
for( ; $it->valid(); $it->next()) {
if($it->isDir() && !$it->isDot()) {
printf('<li class="dir">%s</li>', $it->current());
if($it->hasChildren()) {
$bleh = $it->getChildren();
printf('<ul>%s</ul>');
echo '<ul>' . recurse($bleh) . '</ul>';
}
} elseif($it->isFile()) {
printf('<li class="file">%s (%u Bytes)</li>',
$it->current(), $it->getSize());
}
}
echo '</ul>';
}
recurse(new RecursiveDirectoryIterator('D:/'));
?>
--was--
Note that there have been changes to the SPL iterator method names since this page was first
published. Iterator::hasMore() is now Iterator::valid();
Example ArrayIterator usage:
<?php
$my_array = array(
'One' => 'First Item',
'Two' => 'Second Item',
'Three' => 'Third Item'
);
$ArrayIterator = new ArrayObject($my_array);
for($it = $ArrayIterator->getIterator(); $it->valid(); $it->next()) {
printf('%s => $s <br />', $it->key(), $it->current());
}
?>
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple
treeview of a given directory:
<?php
function recurse($it) {
echo '<ul>';
for( ; $it->valid(); $it->next()) {
if($it->isDir() && !$it->isDot()) {
printf('<li class="dir">%s</li>', $it->current());
if($it->hasChildren()) {
$bleh = $it->getChildren();
printf('<ul>%s</ul>');
echo '<ul>' . recurse($bleh) . '</ul>';
}
} elseif($it->isFile()) {
printf('<li class="file">%s (%u Bytes)</li>',
$it->current(), $it->getSize());
}
}
echo '</ul>';
}
recurse(new RecursiveDirectoryIterator('D:/'));
?>
http://www.php.net/manual/en/ref.spl.php