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…

array, array to xml, php, xml, XML_Serializer

Related:

3 Comments

  1. Comment by Dan Scott on September 18, 2006 1:36 pm

    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]

  2. Comment by Andrew Nagy on September 18, 2006 2:49 pm

    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]

  3. Comment by Chris Sloots on October 8, 2007 10:39 am

    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);

Comments RSS TrackBack Identifier URI

Leave a comment

 

User contributed tags for this post:

1