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

4
  • yes, it can be implemented with SimpleXml. Please clarify what kind of advice are you looking for? Commented Mar 15, 2012 at 13:07
  • For converting your objects to XML see this question: stackoverflow.com/questions/137021/php-object-as-xml-document Commented Mar 15, 2012 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. Commented Mar 28, 2012 at 8: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? Commented Mar 13, 2013 at 16:33

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.