Good things come in twos: Mickey and Donald, Tom and Jerry, yin and yang. It's no surprise then that XML_Serializer has a doppelganger of its own. Called XML_Unserializer, this class can take an XML document and convert it into a series of nested PHP structures, suitable for use in a PHP script. In order to understand how this works, consider the following XML document:
Now, in order to convert this XML document into a PHP structure, simply put XML_Unserializer to work on it, as below:
Here, the unserialize() method accepts either a string containing XML data or an XML file (set the second argument to false or true depending on which one you are passing) and returns a PHP structure representing the XML document. Here's what the output looks like:
Now, in order to access the title of the third book (for example), you would use the notation
which would return
Note that XML_Unserializer uses the type hints generated in the serialization process to accurately map XML elements to PHP data types. If these hints are unavailable (as in the example above), XML_Unserializer will "guess" the type of each value. A look at the source code of the class reveals that "complex structures will be arrays and tags with only CData in them will be strings."
blog comments powered by Disqus |