1

I'm trying to make a simple script which has to convert a PHP array to XML.. but I can't make it work.. The script works fine when the array only has one dimension and when there are more dimensions all nodes are appended to the "root" node

#class
    class XML {
        private $root = '<response />';

        function __construct($root=null){
            $this->root = new SimpleXMLElement($root ? $root:$this->root);
        }

        function encode($arr, $node=null){
            $node = $node ? $node:$this->root;
            foreach($arr as $key => $value){
                if(is_array($value)){
                    $this->encode($value, $node->addChild($key));
                }
                else{
                    $node->addChild($key, $value);
                }
            }
        }

        function output(){
            return $this->root->asXML();
        }
    }


#code

    $arr = array(
        'test' => 'noget',
        'hmmm' => 12,
        'arr' => array(
            99 => 'haha',
            'arr2' => array(
                ),
            'dd' => '333'
            )
        );
    print_r($arr);
    require_once '../class/class.XML.php';
    $XML = new XML();
    $XML->encode($arr);
    echo $XML->output();

#output

    Array
    (
        [test] => noget
        [hmmm] => 12
        [arr] => Array
            (
                [99] => haha
                [arr2] => Array
                    (
                    )

                [dd] => 333
            )

    )
    <?xml version="1.0"?>
    <response><test>noget</test><hmmm>12</hmmm><arr/><99>haha</99><arr2/><dd>333</dd></response>

1 Answer 1

1

You're code looks quite fine to do what you want it to do, however, you must more carefully check for the optional $node parameter in:

function encode($arr, $node=null){
    $node = $node ? $node:$this->root;

I could get it to working like so:

function encode($arr, $node=null){
    $node = null === $node ? $this->root : $node;

An empty simplexml element is false (see the last point in this Converting to boolean list) and as you add an empty child it's always false and you added again to the root element.

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.