php - simpleXML script -
i'm trying make simple script has convert php array xml.. can't make work.. script works fine when array has 1 dimension , when there more dimensions nodes appended "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 $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>
you're code looks quite fine want do, however, must more check optional $node
parameter in:
function encode($arr, $node=null){ $node = $node ? $node:$this->root;
i working so:
function encode($arr, $node=null){ $node = null === $node ? $this->root : $node;
an empty simplexml element false
(see last point in converting boolean list) , add empty child it's false , added again root element.
Comments
Post a Comment