SimpleXML and its Not So Simple To Use Object Model: Problem & Solution
By Angsuman Chakraborty, Gaea News NetworkWednesday, November 16, 2005
SimpleXML is simple to use as its name suggests. However it is a pain when you need to check the value of an element which may or may not exist.
In short using it on XML schema with optional elements is a royal pain. As SimpleXML only creates objects for which data exists, you will have to write ugly code everytime to check for existence of an object before you access its value.
You cannot solve it by simply writing a convenience method. Lets understand the problem and then we will solve it.
The Advantage
SimpleXML is very simple to use. You access elements as you would access an Object hierarchy:
$xml->Items[0]->Request[0]->Errors[0]->Error[0]->Status
The Problem
SimpleXML creates objects only for XML elements which have data (and rightly so). This makes it efficient. However it also makes it harder to use when your schema is flexible with optional elements. Lets take the above example. You cannot safely access Status as above if Errors is an optional element which is only present when there is an error. And you cannot check the existence of Status like this:
isset($xml->Items[0]->Request[0]->Errors[0]->Error[0]->Status)
because Errors may not be present. So to find out if there are any error you first have to check the existence of Errors and then the existance of Status (possibly) before you can actually check the status. And this is true for any depth of the object hierarchy. You can see how quickly this cane become a major pain in the neck. Also you are very likely to miss some and cause maintenance hassles. The code becomes unmaintainable too.
Solution
My solution is to use XPath for such situations. It succintly tells you the availability and value (if available) of a field.
Conclusion
SimpleXML in conjunction with XPath is a very powerful way to process your XML data in PHP.
December 19, 2005: 2:55 am
[...] Reports Sony DRM Rootkit violating several open source licenses, lists Christmas wish from Google AdSense, provides tips on Google Analytics and simplifies SimpleXML for PHP developers. [...] |
November 22, 2005: 8:42 am
[...] Reports Sony DRM Rootkit violating several open source licenses, lists Christmas wish from Google AdSense, provides tips on Google Analytics and simplifies SimpleXML for PHP developers. [...] |
November 22, 2005: 8:37 am
[...] Reports Sony DRM Rootkit violating several open source licenses, lists Christmas wish from Google AdSense, provides tips on Google Analytics and simplifies SimpleXML for PHP developers. [...] |
November 16, 2005: 11:42 pm
[...] Ones SimpleXML and its Not So Simple To Use Object Model: Problem & Solution » SimpleXML doesn’t Work with PHP 5.x: Problem & Solution November 16th, 2005 by AngsumanChakraborty [...] |
Weblog Hosting Blog » Blog Archive » Best of The Fortnight Ending 20th November 2005