PHP Array To XML
I needed a quick, perhaps even sloppy way to output an array as XML. Some Googling turned up a few tools, including Simon Willison’s XmlWriter, Johnny Brochard’s Array 2 XML, Roger Veciana Associative array to XML, and Gijs van Tulder’s Array to XML. Finally, Gijs also pointed me to the XML_Serializer PEAR Package.
In an example of how even the smallest barriers can turn people away, I completely ignored the two possible solutions at PHP Classes, because navigating and using the site sucks. I passed on Willison’s function because, well, it didn’t look like it would do enough of what I wanted. Despite Gijs’ recommendation of the PEAR module, I was happy enough to use his array_to_xml function, as it did what I needed and required the lest work for the moment. I may revisit XML_Serializer sometime, but…
3 Comments
Comments RSS TrackBack Identifier URI
Leave a comment
I agree with you on phpclasses.org; it appears a little bit too informal for my liking — and while the rather strict coding standards that PEAR requires for acceptance of packages can be a barrier for the contributing developer, I’ve found in my ongoing development for File_MARC (http://marc.coffeecode.net) that those guidelines have really increased my faith in the general quality of the code maintained by the PEAR project. The review comments I have received so far have already helped improve my package proposals.
[tags]PEAR[/tags]
I suggest taking a look at the PEAR package, it may be a bit heafty, but it is very worth while.
[tags]PEAR, XML_Serializer[/tags]
May nbe this code fragment helps!
function array_to_xml($aArr, $sName, &$item = null) {
global $dom;
if (is_null($item))
$item = $dom->createElement($sName);
// Loop thru each element
foreach ($aArr as $key => $val) {
if (is_array($val)) {
//
$sub = $dom->createElement($key);
$item->appendChild($sub);
array_to_xml($val, $key, $sub);
} else {
// Add this item
$sub = $dom->createElement($key, $val);
$item->appendChild($sub);
}
}
return $item;
}
$dom = new DOMDocument(’1.0′);
// create root element
$root = $dom->createElement(’bsr’);
$dom->appendChild($root);
// create child element
$info = $dom->createElement(’info’);
$root->appendChild($info);
$aRes = array(
‘first’=>3,
’subarray’=> array(
’sub1′=>’sub1′,
’sub2′=>’sub2′,
’sub3′=>’sub3′
)
‘last’
};
$restree = array_to_xml($aRes, ‘result’);
$info->appendChild($restree);