我正在尝试创建一个简单的脚本,该脚本必须将PHP数组转换为XML。但我不能让它工作..当数组只有一个维数,并且有更多维数时,所有节点都附加到"root“节点上时,该脚本工作得很好
#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>发布于 2011-07-02 21:18:04
您的代码看起来可以很好地完成您想要它做的事情,但是,您必须更仔细地检查中的可选$node参数:
function encode($arr, $node=null){
$node = $node ? $node:$this->root;我可以让它像这样工作:
function encode($arr, $node=null){
$node = null === $node ? $this->root : $node;一个空的simplexml元素是false (see the last point in this list),当您添加一个空子元素时,它总是为false,并且您再次添加到根元素中。
https://stackoverflow.com/questions/6557191
复制相似问题