Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

xml

xsd

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?

like image 434
Edward Tanguay Avatar asked Aug 28 '09 08:08

Edward Tanguay


1 Answers

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

  • libxml_use_internal_errors() to switch to user error handling
  • libxml_get_errors() to retrieve the errors from the libxml error buffer; this will return an array of libXMLError objects
  • libxml_clear_errors() to clear the libxml error buffer

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); 
like image 177
Stefan Gehrig Avatar answered Oct 02 '22 13:10

Stefan Gehrig