HomePHP Page 3 - Main Methods of the DirectoryIterator Class in PHP 5
A standard way to traverse directories: using the DirectoryIterator class - PHP
The DirectoryIterator class is an important part of the Standard PHP Library (SPL). Among other things, it lets you traverse any specified directory with a regular "foreach" loop. In this first article of a three-part series, some of the most relevant methods that come with the “DirectoryIterator” class are covered.
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.