Search code examples
phprecursionopendir

how to turn a recursive function opendir


Would you like to transform the recursive function below. But keeping the filter of allowed file extension (xml).

function lista_xml($path) {
 $xml_array = Array(); 
    $dh = opendir($path); 
      while ( false !== ($file = readdir($dh)) )
    {
        if ( $file=="." || $file==".." || is_dir($file) ) continue; 
        $namearr = explode('.',$file);
        if ($namearr[count($namearr)-1] == 'xml') $xml_array[] = $file; 
    } 
    closedir($dh);
    return $xml_array;
}

My Folder:
Path/directory1/aaa.xml;bbb.xml;
Path/directory1/directory2/xxx.xml;yyy.xml;
Path/directory1/directory2/directory3/ccc.xml;

I want a unique array:
[0] => aaa.xml
[1] => bbb.xml
[2] => xxx.xml
[3] => yyy.xml
[4] => ccc.xml

Solution

  • Make the return variable also an input variable and recursively call itself on subdirectories.

    function lista_xml($path, $xml_array=array()) {
        $dh = opendir($path); 
        while ( false !== ($file = readdir($dh)) )
        {
            if ($file == '.' || $file == '..') continue;
            $file = realpath($path . '/' .basename($file));
    
            $info = pathinfo($file);
            if (isset($info['extension']) && $info['extension'] == 'xml') {
                $xml_array[] = $file;
            } elseif ( $file!='.' && $file!='..' && is_dir($file)) {
                $xml_array = lista_xml($file, $xml_array);
            }
        } 
        closedir($dh);
        return $xml_array;
    }