Hello everyone!
This is my first time posting on this forum with what I think should be a fairly easy problem to solve...

Ok. I have a script here that I found that looks through a directory and outputs an XML file tree by recursively sorting through the files and folders.

The problem is that there is no real order, files are arranged pretty much randomly. I would like the files to be ordered alphabetically in the output.

I know there is an easy solution to this, but I have yet to get one to work.

PLEASE HELP ME!!! :queasy:

Here is my code:

<?php 
// _xmltree.php a utiliity to produce an XML directory tree 
$directory=$_GET['d']; 
$rh = fopen('_xmltree.txt', 'w'); 
global $rh; 
print "<pre> \n"; 
// Argument is where list should start ./ = current directory 
directory_list("./".$directory,''); 
print "</pre> \n"; 

function directory_list($address, $level, $tabs='') { 
global $rh; 
if ($handle = opendir($address)) { 
$tabs .= "\t"; 
while (false !== ($file = readdir($handle))) { 
if (is_dir("$address$file") && strpos($file, ".") !== 0) { 
if (0 == strncmp($file, "_", 1)) continue; 
fwrite($rh, $tabs.'<'.$file.'>'."\n"); 
print $tabs."&lt;$file&gt;\n "; 
directory_list("$address$file/", $file, $tabs); // Makes Listing Recursive 
} 
} 

rewinddir ($handle); 

while (false !== ($file = readdir($handle))) { 
$URL = $address . $file; 
if (is_dir("$URL") || strpos($file, ".") === 0) continue; 
if (0 == strncmp($file, "_", 1)) continue; 
fwrite($rh, '<filename>'.$file.'</filename>'."\n"); 
print $tabs."&lt;filename&gt;$file&lt;/filename&gt;\n "; 
} 
closedir($handle); 
$tabs = substr($tabs,0,strlen($tabs)-1); 
if($level != '') 
{ 
fwrite($rh, $tabs."</$level>\n"); 
print $tabs."&lt;/$level&gt;\n"; 
} 
} 
} 

?> 

    Yes, I figured as much... alas I am a real begginer still. Is there anyway that you could show me with my code how to do this? I am kind of in a jam right now, but will learn the method when I have more time...

      Here is a shortened version of the recursive function, which places the information into two arrays; one for files, the other for directories. It also sorts the arrays into order.

      <?php
      function read_dir($dir) {
         $path = opendir($dir);
         while (false !== ($file = readdir($path))) {
             if($file!="." && $file!="..") {
                 if(is_file($dir."/".$file))
                     $files[]=$file;
                 else 
                     $dirs[]=$dir."/".$file;            
      } } if($dirs) { natcasesort($dirs); foreach($dirs as $dir) { echo $dir; read_dir($dir); } } if($files) { natcasesort($files); foreach ($files as $file) echo $file } closedir($path); } ?>

      All you need to add to this function is your tabs for directory level depth, and a simple loop through the $file array to create your XML file.

        Thanks a lot Pete,
        It works great!
        Just in time!

          Write a Reply...