views:

122

answers:

2

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?

A: 

If you only need to print, you can define your custom error handler to print the error.

Zed
+4  A: 

I think you can use libxml's error handling functions for this one:

Simple 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);
Stefan Gehrig