[英]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?
有什么想法可以使其解析所有目录中的所有文件吗?
There are a number of problems with your script, mostly around the foreach
. 您的脚本有很多问题,主要是在
foreach
周围。
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
。 ScanFiles::calculateEAXML($dir);
: You're scanning the same directory again, and doing nothing with the response. $df = opendir($dir . $file);
: If the file isn't a directory, you're trying to open it as a directory. 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.