clarkk
clarkk

Reputation: 27689

simpleXML script

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>

Upvotes: 1

Views: 194

Answers (1)

hakre
hakre

Reputation: 197795

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.

Upvotes: 1

Related Questions