Home » Php » How to get the warning message as a string when validating XML with schemaValidate() in PHP?

How to get the warning message as a string when validating XML with schemaValidate() in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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?

How to&Answers:

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); 

Answer:

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

Answer:

here is how i did it:

$errs = [ ];
set_error_handler ( function ($severity, $message, $file, $line) use (&$errs) {
    $errs [] = $message;
} );
$validated = $domd->schemaValidate ( 'factinv-3-0.xsd' );
restore_error_handler ();

error descriptions are now in $errs, if any.