1

I have a bunch of PHP web services that construct JSON objects and deliver them using json_encode.

This works fine but I now have a requirement that the web services can also deliver in XML, depending on a given parameter.

I want to stay away from PEAR XML if possible, and hopefully find a simple solution that can be implemented with SimpleXML.

Can anyone give me any advice?

Thanks

adam
  • 22,404
  • 20
  • 87
  • 119
  • yes, it can be implemented with SimpleXml. Please clarify what kind of advice are you looking for? – Gordon Mar 15 '12 at 13:07
  • For converting your objects to XML see this question: http://stackoverflow.com/questions/137021/php-object-as-xml-document – chiborg Mar 15 '12 at 13:16
  • See above - I want to stay away from PEAR XML if possible. I want to use SimpleXML. I just want to know if there is an easy function, as easy as json_encode for instance, that will convert JSON to XML. – adam Mar 28 '12 at 08:19
  • @adam - I find myself with the same need to feed json to SimpleXML, and the same desire to avoid any PEAR dependencies...did you have any luck finding a solution for this? – hardba11 Mar 13 '13 at 16:33

1 Answers1

3

You can create an associative array using json_decode($json,true) and try the following function to convert to xml.

function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = function($f,$c,$a) {
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }
    };
    $f($f,$xml,$ar);
    return $xml->asXML();
} 

// usage
$data = json_decode($json,true);
echo assocArrayToXML("root",$data);