One of PHP5's most interesting new features is the addition of Iterators, a collection of ready-made interfaces designed to help in navigating and processing hierarchical data structures.

These Iterators significantly reduce the amount of code required to process an XML document tree or a file collection. A number of Iterators are available, including the ArrayIterator, CachingIterator, LimitIterator, RecursiveIterator, SimpleXMLIterator and DirectoryIterator.

The DirectoryIterator provides a quick and efficient way of processing the files in a directory; with a little creative coding, it can also be used to recursively process a nested directory tree. Both these tasks can be accomplished using just a few lines of code, representing a significant improvement over the "standard" way of doing things.

Processing a single-level directory

Let's begin with something simple: processing a single-level directory. Type (or copy) the following script, altering the directory path to reflect your local configuration:

<?php
$it = new DirectoryIterator("/tmp/mystuff");
foreach( as ) {
  if (!->isDot()) {
    echo . "\n";
    }
  }
?>

When you view the output of this script in your browser, you should see a list of the files in the named directory. How did this happen? Well, the DirectoryIterator class provides a pre-built interface to iterating over the contents of a directory; once instantiated with the location of the target directory, it can then be processed as though it were a standard PHP array, with each element representing a file in the directory. Note the use of the isDot() method to filter out the "." and ".." directories, respectively.

Processing a nested directory tree

Recursively processing a nested directory tree is almost as simple. In this case, the DirectoryIterator needs to check each object it encounters within the first-level directory, determine whether it is a file or directory, and, if a directory, drill one level deeper to examine the next level of contents. This sounds fairly complex, and in the past could easily add up to 15-plus lines of code.

With PHP5, though, all you need are two new Iterators: the RecursiveDirectoryIterator and the RecursiveIteratorIterator, which together incorporate all the above functionality. Take a look at the code below:

<?php
$it = new RecursiveDirectoryIterator("/tmp");
foreach(new RecursiveIteratorIterator() as ) {
  echo . "\n";
  }
?>

In this case, the output should now include a list of all the files and directories under the starting directory. Needless to say, this kind of built-in recursive interface is very handy for situations that require you to process all the files under a particular directory level -- for example, when recursively compressing a directory tree, or altering group/owner permissions on a series of nested files.

A real-world application: Printing a directory tree

A common application of directory recursion involves printing a graphical directory tree. With Iterators, this task is a snap, because included within the Iterator class documentation is an example class written specifically for this purpose. The DirectoryTreeIterator (credit: Marcus Boerger) provides additional enhancements to the RecursiveIteratorIterator discussed previously, most notably ASCII markers that represent depth and location within the tree structure.

You can examine the source code for this example class on the php.net website.

The code below shows how the DirectoryTreeIterator can be used.

<?php
$it = new DirectoryTreeIterator("/tmp/cookbook/");
foreach( as ) {
echo . "\n";
}
?>
And here's a brief snippet of the output you might see: |-ch01
| |-recipe01
| | |-example01.php
| | \-example02.php
| |-recipe02
| | |-example01.php
| | \-example02.php
| |-recipe03
| | \-example01.php
...

To better understand the value-add of these various DirectoryIterators, try coding the three applications demonstrated in this tutorial using standard file and directory functions. Once you're done, you'll have a new appreciation for the simplicity and ease of use the DirectoryIterators bring to PHP5. Happy coding!

Wide World of Web This was published in Wide World of Web, check every Wednesday for more stories

Related links

Comments

1

Binny V A - 19/06/08

I have created a function for this - it does not use DirectoryIterator - but it has a similar functionality.
<a href="http://www.bin-co.com/php/scripts/filesystem/ls/">ls() - Return Folder Contents</a>

» Report offensive content

2

Jackos - 20/06/08

if i'm not mistaken, there's something wrong with your code:
...
foreach( as ) {
if (!->isDot()) {
echo . "\n";
...
it lacks variables (at least this particular fragment)
at first i thought that the code parser on this website strips them off but apparently it's not the case - the $it is still there

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

2

Jackos - 20/06/08

if i'm not mistaken, there's something wrong with your code: ... foreach( as ) { if (!->isDot()) { echo ... more

1

Binny V A - 19/06/08

I have created a function for this - it does not use DirectoryIterator - but it has a similar functionality. <a href="http://www.bin-co.com/php/scripts/filesystem/ls/">ls() ... more

Log in


Sign up | Forgot your password?

  • Staff XP stays on life support for longer

    This week's Roundup looks at Microsoft's decision to extend the life of Windows XP, the release of Microsoft Surface SDK, Firefox's new Geode plug-in, Yahoo's new tool -- Smush It and more. Read more »

    -- posted by Staff

  • Chris Duckett The good and truly awful celluloid depictions of computers

    Ever wonder why your lawyer uncle leaves the room whenever you turn over to Boston Legal? Or why your forensic science cousin can't stand crime drama? You know the answer: it’s the horrid trivialisation and dumbing down of an occupation to make it appear entertaining. Sometimes it is so unbelievable that it actually hurts and yelling at the screen is the only outlet. Read more »

    -- posted by Chris Duckett

  • Brendon Chase Apple's iPhone engineers to tour Sydney, Melbourne

    Aussie developers will be able to get up close and personal with some of the iPhone engineers in November to learn how to build applications for the platform. Read more »

    -- posted by Brendon Chase

What's on?