Just a short function that checks if a XML file’s structure is valid:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/**
* Checks if a XML file's structure is valid.
* @author Julius Beckmann <php@h4cc.de>
* @param $file string
* @return bool
*/
function isXmlStructureValid($file) {
$prev = libxml_use_internal_errors(true);
$ret = true;
try {
new SimpleXMLElement($file, 0, true);
} catch(Exception $e) {
$ret = false;
}
if(count(libxml_get_errors()) > 0) {
// There has been XML errors
$ret = false;
}
// Tidy up.
libxml_clear_errors();
libxml_use_internal_errors($prev);
return $ret;
} |
I had to use libxml_use_internal_errors, because otherwise PHP would output a Warning like this: “PHP Warning: SimpleXMLElement::__construct() …”