Re: Validating XML

From: Date: Thu, 17 Jun 2004 07:25:42 +0000
Subject: Re: Validating XML
References: 1 2 3 4 5  Groups: php.xml.dev 
Request: Send a blank email to php-xml-dev+get-389@lists.php.net to get a copy of this message
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 -- adam@trachtenberg.com author of o'reilly's php cookbook avoid the holiday rush, buy your copy today!

« previous php.xml.dev (#389) next »