Main Methods of the DirectoryIterator Class in PHP 5 - A standard way to traverse directories: using the DirectoryIterator class
(Page 3 of 5 )
As I said right at the beginning of this article, the “DirectoryIterator” class bundled with the SPL package allows you to traverse any directory by using a typical “foreach” loop. Now, keeping in mind the example that you saw in the prior section, have a look at the following one, which shows why the “DirectoryIterator” class can be a real time saver:
// traverse directory with 'DirectoryIterator' class
$dirProc=new DirectoryIterator('default_path/');
foreach($dirProc as $dirContent){
echo $dirContent.'<br />';
}
Did you think that traversing directories with this class was much harder? Not at all! As you can appreciate, first I created an instance of the class, and passed to its constructor the path of the directory being read. Next, I used a simple “foreach” loop, handy for reading the respective contents.
Obviously, this short code snippet outputs the same results that you saw in the previous section. They’re as follows:
.
..
file1.txt
file2.txt
Wasn’t that great? With a few lines of code you get the same results, and all without having to code a custom class. However, this is only a humble beginning, since the “DirectoryIterator” class features plenty of useful methods, which can be used for processing directories in all sorts of clever ways.
Since you have now realized the capabilities that come with the “DirectoryIterator” class, in the next few lines I’ll provide you with some helpful pointers on how to use some of its most significant methods. Therefore, please read the following section.
Next: A deeper look at the DirectoryIterator class: using the key() and current() methods >>
More PHP Articles
More By Alejandro Gervasio