1

I am trying to get all XML files in my 10 subfolders and parse them. 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?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Jack
  • 857
  • 14
  • 39

2 Answers2

0

This is what glob is for:

foreach (glob("*.xml") as $filename) {
    // do sth with the file, $filename holds the current file
}
Jan
  • 42,290
  • 8
  • 54
  • 79
0

There are a number of problems with your script, mostly around the foreach.

  1. if(is_dir($folderName)): The variable $folderName doesn't exist. I would assume that you should have $file there.
  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.

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;    
}
samlev
  • 5,852
  • 1
  • 26
  • 38