i suppose this is what youre looking for ? you can tailor it to your needs of course :) <?php $it = new RecursiveDirectoryIterator('.'); $isFirstDir = true; $fileList = array(); $dynfile = fopen('sortedFiles', 'w+'); $theRecursiveIteratorIterator = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach ($theRecursiveIteratorIterator as $path){ if($path->isDir()){ /// drop the name of the directory into the results fwrite($dynfile, 'Directory: ' . (string) $path . PHP_EOL); if($isFirstDir) { // just update the flag on the first dir $isFirstDir = false; } else { sort($fileList); // sort the list however you like /// iterate over the sorted list, placing them in the output file foreach($fileList as $sortedDirFile) { fwrite($dynfile, $sortedDirFile . PHP_EOL); } $fileList = array(); // clear the list for the next directory } }else{ /// place the current path to a file in the list $fileList[] = (string) $path; } } fclose($dynfile); ?> -nathan