![]()
Let’s face it… parsing XML is boring and usually a pain in the butt, especially when you need to translate it to a hierarchy of PHP objects.
This is why I have decided to create Hitch which is based on Java’s JAXB annotations. Hitch is build on top of doctrine-common which provides easy to use annotation parsing from PHP docblocks.
Let’s say you have the following XML document structure:
-
-
<catalog>
-
<products>
-
<product id="1" name="Product 1">
-
<description>Product Description</description>
-
<price>$100</price>
-
</product>
-
</products>
-
</catalog>
You would map this to a Calalog class like this:
-
-
/**
-
* @xml:XmlObject
-
*/
-
class Catalog
-
{
-
/**
-
* @xml:XmlList(name="product", wrapper="products", type="Hitch\Demo\Entity\Product")
-
*/
-
protected $products;
-
-
// ... getters/setters ...
-
}
-
-
/**
-
* @xml:XmlObject
-
*/
-
class Product
-
{
-
/**
-
* @xml:XmlAttribute
-
*/
-
protected $id;
-
-
/**
-
* @xml:XmlAttribute
-
*/
-
protected $name;
-
-
/**
-
* @xml:XmlElement
-
*/
-
protected $description;
-
-
/**
-
* @xml:XmlElement
-
*/
-
protected $price;
-
-
// ... getters/setters ...
-
-
}
Now you can simply parse the XML to an object graph like this:
-
-
// create our new HitchManager
-
$hitch = new HitchManager();
-
$hitch->setClassMetaDataFactory(new ClassMetadataFactory(
-
new AnnotationLoader(new AnnotationReader()),
-
new ArrayCache()));
-
-
// get xml from somewhere
-
$xml = file_get_contents('myxml.xml');
-
-
// unmarshall xml to a Catalog object
-
$catalog = $hitch->unmarshall($xml, "My\Namespace\Catalog");
-
-
// do something with the object
-
foreach($catalog->getProducts() as $product){
-
echo $product->getName();
-
}
Hitch contains a full demo showing all the possible mappings, so check out the whole project here:
https://github.com/lampjunkie/xml-hitch