简体   繁体   中英

PHP readdir to find xml

I inherited a piece of code that has suddenly stopped working. I've isolated the code down to it appears this function is no longer reading the directory and locating the xml file found in it for later processing. I've uploaded versions of the xml file with uppercase and lowercase .xml/.XML extension with the same result: NO XML FILE FOUND

I've verified that the print_r is in fact reading the correct directory where the xml file resides. There are other files in the directory but that has been the case for years. Did something change recently in PHP to stop this code from working?

function GetXMLFile($path) {
    $path .= "/";
    print_r($path); 
    $filename = "";
        if ($handle = opendir($path)) {
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (GetFileExtention($path . strtolower($file)) =="XML") {
                        $filename = $file;      
                    }
                }
            }
            closedir($handle);
        }

        return $filename;

}

Later in the code the function is called that is producing the NO XML error. I've confirmed the $config['xml_dir'] variable below matches the print_r directory location above as well.

$cur_xml_file = GetXMLFile($config['xml_dir']);

if ($cur_xml_file == "") {
    echo "NO XML FILE FOUND";
    exit(0);    
}

No, nothing has changed in PHP recently that would cause the code you show to stop functioning. If it doesn't work anymore, the error is somewhere else.

Then again, that's a lot of code to find a file. Why don't you just do change it to

function GetXMLFile($path) {
    $all_xml_files = glob("$path/*.{xml,XML}", GLOB_BRACE);
    return !empty($all_xml_files) ? realpath($all_xml_files[0]) : "";
}

That will return the absolute path of the first file with an .XML or .xml extension in the given $path or an empty string if no files are found or an error occured.

See if the error goes away when you change it to that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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