PHP获取子目录中的所有文件

时间:2015-10-13 14:40:09

标签: php xml parsing

我试图在我的10个子文件夹中获取所有XML文件并解析它们。为此,我有以下代码:

public static function calculateEAXML ($dir) {
$dh  = opendir($dir);
$folderNames = array();
$arr = array();
while (false !== ($folderName = readdir($dh))) {
  if ( $folderName[0] == "." || (substr($folderName, -3) == "zip") ) {continue;}
  $folderNames[] = $folderName; 
  $dom = new DOMDocument;
  $dom->validateOnParse = true;
  foreach ($folderNames as $file) 
{
    if(is_dir($folderName)){ScanFiles::calculateEAXML($dir);}
    else{
    $df  = opendir($dir . $file);
    while (false !== ($file = readdir($df))) 
    {
        if ($file == "." || $file == ".."  ) {continue;}
        $dom->Load($dir . $folderName . "/" . $file);
        $arr[] = XML2Array::createArray($dom);
    }
  }
}
  return $arr;    
}
}

事情是它只在一个目录中解析文件而完全忽略另一个目录。有没有想法如何解析所有目录中的所有文件?

2 个答案:

答案 0 :(得分:0)

这是glob的用途:

foreach (glob("*.xml") as $filename) {
    // do sth with the file, $filename holds the current file
}

答案 1 :(得分:0)

您的脚本存在许多问题,主要是foreach

  1. if(is_dir($folderName)):变量$folderName不存在。我认为你应该$file
  2. ScanFiles::calculateEAXML($dir);:您再次扫描同一目录,并且没有对响应做任何处理。
  3. $df = opendir($dir . $file);:如果文件不是目录,则您尝试将其作为目录打开。
  4. 您的foreach循环位于while循环内。
  5. 这是尝试解决这些问题:

    public static function calculateEAXML($dir) {
        $dh  = opendir($dir);
        $folderNames = array();
        $arr = array();
    
        // Get all files and folders in the current directory
        while (false !== ($folderName = readdir($dh))) {
            if ($folderName[0] == "." || (substr($folderName, -3) == "zip")) {
                continue;
            }
            $folderNames[] = $folderName;
        }
    
        foreach ($folderNames as $file) {
            $filename = $dir . '/' . $file;
            if(is_dir($filename)){
                $arr = array_merge($arr, ScanFiles::calculateEAXML($filename));
            } else {
                $dom = new DOMDocument;
                $dom->validateOnParse = true;
                $dom->Load($filename);
                $arr[] = XML2Array::createArray($dom);
            }
        }
        return $arr;    
    }