Update: Read about Hitch, my JAXB-like XML annotation mapper for PHP 5.3: Introducing Hitch
Lately I have been doing alot of Java development especially in regards to web service development and consumption. One of the tools that I have relied on heavily is the JAXB project to consume and create XML feeds. This has been a godsend and made my life easy when parsing and creating XML. By just using a small amount of code and annotations parsing XML is a breeze.
After using JAXB for awhile, it got me thinking….why doesn’t PHP have something like this…how hard would it be to create? On the PHP side of things I have been in love with SimpleXML since I first started using it a number of years ago. Just like the name implies, it is relatively simple. But, could something be developed that would be even simpler like JAXB?
The thing that really makes parsing XML with JAXB easy is the ability to use annotations to map classes and properties to XML nodes. Of course PHP doesn’t have built-in support for annotations, but this can be achieved by using the Extended Reflection API or using a project built on top of that such as addendum. It would also be possible to create a PHP extension to handle this in a much more efficient manner.
This is how I envision being able to parse (unmarshal) XML to a PHP object graph:
Given the following sample XML:
-
-
<result>
-
<ads>
-
<ad url="http://ad1-url">
-
<title>My Title</title>
-
<description>Some Description</description>
-
</ad>
-
<ad url="http://ad2-url">
-
<title>My Title</title>
-
<description>Some Description</description>
-
</ad>
-
</ads>
-
</result>
Convert to an object graph like this:
-
-
/**
-
* @XmlRoot(name="result")
-
*/
-
class Result {
-
-
/**
-
* @XmlCollection(name="ads")
-
* @var array
-
*/
-
private $ads;
-
-
// getters/setters
-
}
-
-
/**
-
* @XmlElement(name="ad")
-
*/
-
class Ad {
-
-
/**
-
* @XmlAttribute(name="url")
-
* @var string
-
*/
-
private $url;
-
-
/**
-
* @XmlElement(name="title")
-
* @var string
-
*/
-
private $title;
-
-
/**
-
* @XmlElement(name="description")
-
* @var string
-
*/
-
private $description;
-
-
// getters/setters
-
}
-
-
// grab an XML feed
-
$xml = file_get_contents('some-xml-from-somewhere.xml');
-
-
// create our unmarshaller and tell it where to find classes to unmarshal to
-
$unmarhaller = new SimplerXmlUnmarshaller("/package/location");
-
-
// unmarshal to an object graph
-
$result = $unmarshaller->unmarshal($xml);
-
-
// loop through objects
-
foreach($result->getAds() as $ad){
-
echo $ad->getUrl() . '<br />' . $ad->getTitle() . '<br />' . $ad->getDescription() . '<br />';
-
}
Hopefully in the near future I will get time to develop a proof of concept to see if this works and take it from there…