I have this code to validate an XML file against an XSD file:
$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);
if ($dom->schemaValidate($schema)) {
print "$file is valid.\n";
} else {
print "$file is invalid.\n";
}
If the xml file is invalid, then it says that it is invalid. The reason it is invalid (e.g. price is not an integer), however, is only given in a PHP warning, which I have to suppress so that user doesn't see it (with error_reporting(0)).
How can I get the text of that message and pass it on to the user, as I would do in C# with a try/catch?
I think you can use libxml
's error handling functions for this one:
libxml_use_internal_errors()
to switch to user error handlinglibxml_get_errors()
to retrieve the errors from the libxml
error buffer; this will return an array of libXMLError
objectslibxml_clear_errors()
to clear the libxml
error bufferSimple example:
$file = 'test.xml';
$schema = 'test.xsd';
$dom = new DOMDocument;
$dom->load($file);
libxml_use_internal_errors(true);
if ($dom->schemaValidate($schema)) {
print "$file is valid.\n";
} else {
print "$file is invalid.\n";
$errors = libxml_get_errors();
foreach ($errors as $error) {
printf('XML error "%s" [%d] (Code %d) in %s on line %d column %d' . "\n",
$error->message, $error->level, $error->code, $error->file,
$error->line, $error->column);
}
libxml_clear_errors();
}
libxml_use_internal_errors(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With