简体   繁体   English

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

[英]PHP getting all files in subdirectories

I am trying to get all XML files in my 10 subfolders and parse them. 我试图在我的10个子文件夹中获取所有XML文件并对其进行解析。 To do that I have the following code: 为此,我有以下代码:

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;    
}
}

The thing is it parses the files only in ONE directory completely ignoring the other. 问题是它只解析一个目录中的文件,而完全忽略另一个目录。 Are there any ideas how to make it parse all the files in ALL directories? 有什么想法可以使其解析所有目录中的所有文件吗?

This is what glob is for: 这是glob的用途:

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

There are a number of problems with your script, mostly around the foreach . 您的脚本有很多问题,主要是在foreach周围。

  1. if(is_dir($folderName)) : The variable $folderName doesn't exist. if(is_dir($folderName)) :变量$folderName不存在。 I would assume that you should have $file there. 我认为您应该在那里有$file
  2. ScanFiles::calculateEAXML($dir); : You're scanning the same directory again, and doing nothing with the response. :您将再次扫描同一目录,并且对响应不执行任何操作。
  3. $df = opendir($dir . $file); : If the file isn't a directory, you're trying to open it as a directory. :如果文件不是目录,则尝试将其作为目录打开。
  4. Your foreach loop is inside the while loop. 您的foreach循环位于while循环内。

Here's an attempt at fixing those problems: 这是解决这些问题的尝试:

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;    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM