Wednesday, November 7, 2012

Recursively walk through directory tree

If you need to get all files (or also folders) from some folder and it's subfolders recursively, use following simple construction:

    $folder = '/path/to/folder';

    $objects = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($folder),
        RecursiveIteratorIterator::SELF_FIRST);

    foreach ($objects as $object)
    {
        /**
         * $object is instance of SplFileInfo
         */

        if ($object->isFile())
        {
            echo $object->getExtension();
            echo $object->getRealPath();
        }
    }
Check also PHP manual
     http://php.net/manual/en/class.recursiveiteratoriterator.php
     http://php.net/manual/en/class.recursivedirectoryiterator.php
     http://php.net/manual/en/class.splfileinfo.php







No comments: