2015-10-13 118 views
0

我試圖讓所有的XML文件在我的10個子文件夾,並解析這些文件。要做到這一點,我有以下代碼:PHP越來越子目錄

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

的事情是它只能在一個目錄完全忽視了其他解析文件。有沒有任何想法如何讓它解析所有目錄中的所有文件?

+1

也許這將幫助:http://stackoverflow.com/a/1860417/5440709 – Kanti

回答

0

有許多與你的腳本的問題,主要是圍繞foreach

  1. if(is_dir($folderName)):變量$folderName不存在。我會假設你應該有$file那裏。
  2. ScanFiles::calculateEAXML($dir);:您再次掃描相同的目錄,並且對響應無所作爲。
  3. $df = opendir($dir . $file);:如果文件不是目錄,則試圖將其作爲目錄打開。
  4. foreach循環是while循環中。

這裏是一個企圖在修復這些問題:

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

非常非常感謝!按預期工作! – Jack

0

這是glob是:

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