Aug
4
2013

PHP validate XML against XSD for more detailed error.

This is the code to validate some XML against a XML schema using PHP5′s “schemaValidate();”

 

PHP Code :

function libxml_display_error($error)
{
$return = “<br/>\n”;
switch ($error->level) {
case LIBXML_ERR_WARNING:
$return .= “<b>Warning $error->code</b>: “;
break;
case LIBXML_ERR_ERROR:
$return .= “<b>Error $error->code</b>: “;
break;
case LIBXML_ERR_FATAL:
$return .= “<b>Fatal Error $error->code</b>: “;
break;
}
$return .= trim($error->message);
if ($error->file) {
$return .=    ” in <b>$error->file</b>”;
}
$return .= ” on line <b>$error->line</b>\n”;

return $return;
}

function libxml_display_errors() {
$errors = libxml_get_errors();
foreach ($errors as $error) {
print libxml_display_error($error);
}
libxml_clear_errors();
}

// Enable user error handling
libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load(‘eMP-example.xml’);

if (!$xml->schemaValidate(‘schema.xsd’)) {
print ‘<b>DOMDocument::schemaValidate() Generated Errors!</b>’;
libxml_display_errors();
}
else {
echo “validated”;
}

 


Leave a comment

You must be logged in to post a comment.




Member Area