1

Im trying to traverse a file tree in a self first order, so I would expect the files in a directory to be all listed first before going down to the next level. However for some reason this is not happening. Please find below my code

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($f["path"],   RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);

foreach ($it as $fileObject) {
    echo $fileObject."\n";
}

And this prints the following example (if my input directory is /data/documents/

  • /data/documents/file name 1.pdf
  • /data/documents/filename 2.pdf
  • /data/documents/dir A/file 4.jpg
  • /data/documents/dir A
  • /data/documents/file name 5.pdf
  • /data/documents/dirB/filex.pdf
  • /data/documents/dirB/filey.jpg
  • /data/documents/dirB/dirC/filew.pdf
  • /data/documents/dirB/dirC/filev.pdf
  • /data/documents/dirB/dirC
  • /data/documents/dirB
  • /data/documents/file name r.pdf

Yes, the files and sometimes the directories have spaces in their naming. I'm running this on the command line, using php version PHP 5.3.3 (cli) (built: Dec 11 2013 03:29:57)

Any help would be greatly appreciated.

UPDATE: I would expect the following output instead;

  • /data/documents/dir A
  • /data/documents/dir A/file 4.jpg
  • /data/documents/dirB
  • /data/documents/dirB/filex.pdf
  • /data/documents/dirB/filey.jpg
  • /data/documents/dirB/dirC
  • /data/documents/dirB/dirC/filew.pdf
  • /data/documents/dirB/dirC/filev.pdf
  • /data/documents/file name 1.pdf
  • /data/documents/filename 2.pdf
  • /data/documents/file name 5.pdf
  • /data/documents/file name r.pdf

1 Answers1

3

Although a long long time ago you asked the question, Here is a solution. Also, I was looking an answer for the same problem.

<?php

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("/path"),RecursiveIteratorIterator::SELF_FIRST);

    $html = "";

    foreach($iterator as $folder)
    {
      if($folder->isDir())
      {
        $all_files = glob($folder->getRealpath()."/*.*");

        foreach ($all_files as $filename)
        {

          $html .= $filename."<br>";
        }
      }
    }
      echo $html;
    ?>
Mohamed Shahid
  • 476
  • 5
  • 18