Re: [PHP-XML-DEV] Validating XML
[email protected] (Adam Maccabee Trachtenberg) Thu, 17 Jun 2004 03:25:42 -0400 (EDT)
| Newsgroups | php.xml.dev |
|---|---|
| Message-ID | <[email protected]> |
On Wed, 16 Jun 2004, Adam Maccabee Trachtenberg wrote:
> Also, it really should return false. What does it return? Does it die
> with a fatal error?
I checked at least with my version of PHP 5 (which is a very recent
CVS checkout), this method return false when it encounters a
validation error.
> I think there's a way, but it's a little kludgy. You could define a
> custom error handler function to handle these messages using
> set_error_handler(). After you're finished, call
> restore_error_handler() to go back to normal error handling.
Here's some code that implements this:
function schemaErrorHandler($errno, $errstr, $errfile, $errline) {
print "Your file fails to validate because: $errstr\n";
}
$dom = new DOMDocument;
$dom->load('library1.xml');
set_error_handler('schemaErrorHandler');
if ($dom->schemaValidate('library1.xsd')) {
print "library1 valid\n";
} else {
print "library1 invalid\n";
}
restore_error_handler();
if ($dom->schemaValidate('library1.xsd')) {
print "library1 valid\n";
} else {
print "library1 invalid\n";
}
Let's assume that your file (library1.xml) fails to validate. In this
case, you'll see something like this:
Your file fails to validate because: Element name: failed to validate basic type date
Your file fails to validate because: Element name: failed to validate basic type date
library1 invalid
PHP Warning: Element name: failed to validate basic type date in...
PHP Warning: Element name: failed to validate basic type date in...
library1 invalid
As you see, the first time the custom error handler has trapped the
error and printed out the message that is defined in the function. The
second time, after the native error handling code has been restored,
PHP prints out a warning.
It's not the most flexible of solutions, because it's not like you can
return values from the error handler, but it's better than nothing.
-adam
--
[email protected]
author of o'reilly's php cookbook
avoid the holiday rush, buy your copy today!