Jump to content
Larry Ullman's Book Forums

Recommended Posts

I am just finishing CH 13 of the book, on XML, and I am a little confused with the schemas.  How come I am allowed to open an XML file if it doesn't adhere to its schema?  It seems all a web browser cares about is properly formatted XML regardless of what elements the schema calls for.  My research points to php functions that validate the xml based on a scheme, which is great, but why wouldn't the schema be read on its own when opening a raw XML file?  It seems like the browser doesn't even care if the external schema file exists so why even reference it in the XML?

 

In order to validate it I came up with tis code...

 

$xml = new DOMDocument();
$xml -> load('books4.xml');
 
if (!$xml->schemaValidate('collection.xsd')) { 
   echo "invalid<p/>";
else { 
   echo "validated<p/>"; 
 
I had to separately point to the schema in this code, it could not even "read" the linked schema in the XML so again why put it in the XML?  Or would an expansion of the SimpleXML parser have an ability to extract that info and validate the XML against the XSD?
 
Any clarification would be greatly appreciated!
Link to comment
Share on other sites

The difference here is that DOMDocument is an object that builds a structure internally by loading XML. To make it as usable as possible, the API was probably written to allow invalid XML. In other words, that an implementation choice.

 

Next, you need to study the API better. While DOMDocument::schemaValidate() takes the Schema as String param, DomDocument::validate() will validate according to the internally linked schema. By changing your code to the following, you should be able to remove the reference to the DTD.

$xml = new DOMDocument();
$xml->load('books4.xml');
 
if ( ! $xml->validate() ) { 
   echo "invalid<p/>";
} 
else { 
   echo "validated<p/>"; 
} 

If that should not work for any reasons, you might need to play around with some constants/changing some properties. Here's a link describing a solution: http://www.php.net/manual/en/domdocument.validate.php#84905

 

Good luck.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...