请教大神数组转XML格式问题
<br /> <?xml version="1.0" encoding="utf-8"?><br /> <nodes><br /> <node id="c5569e2c-0f4a-4ec2-86ba-736b79eca18c" name="A公司"<br /> type="0"><br /> <node id="4f2b55e9-e10a-496b-8bca-60e6f26daee5" name="部门1" type="1"><br /> <node id="363" name="叶子1" type="2" playurl="http://XXXXXXX363" /><br /> </node><br /> <node id="0c5ce42f-ba31-4b7a-8173-79ecae4a73ca" name="部门2" type="1"><br /> <node id="241" name="叶子1" type="2" playurl="http://xxxxx=241" /><br /> <node id="356" name="叶子1" type="2" playurl="xxxxxxxxx=356" /><br /> </node><br /> </node><br /> </nodes><br />
<br /> function arrayToXml($arr, $xmlDoc = 0, $item = 0)<br /> {<br /> /*判断是否已为xml*/<br /> if (!$xmlDoc)<br /> {<br /> $xmlDoc = new DOMDocument("1.0");<br /> }<br /> /*判断是否为子节点*/<br /> if (!$item)<br /> {<br /> $item = $xmlDoc->createElement("nodes","UTF-8");<br /> $xmlDoc->appendChild($item);<br /> }<br /> /*将数组数据按“键=>值”方式,循环取出并写入dom树*/<br /> foreach ($arr as $key=>$val)<br /> {<br /> /*增加子节点名和值*/<br /> $itemX = $xmlDoc->createElement(is_string($key) ? $key:"node");<br /> $item->appendChild($itemX);<br /> /*如果数组内某一元素的值也是数组,则进行递归*/<br /> if (!is_array($val))<br /> {<br /> $text = $xmlDoc->createTextNode($val);<br /> $itemX->appendChild($text);<br /> }<br /> else<br /> {<br /> $this->arrayToXml($val,$xmlDoc,$itemX); //在类中调用需加$this-><br /> }<br /> }<br /> return $xmlDoc->saveXML(); //返回xml数据,可以把返回数据直接写入*.xml文件即可生成xml文件<br /> }<br />
$ar = array(<br /> array( 'id' => "c5569e2c-0f4a-4ec2-86ba-736b79eca18c", 'name' => "A公司", 'type' => "0",<br /> array( 'id' => "4f2b55e9-e10a-496b-8bca-60e6f26daee5", 'name' => "部门1", 'type' => "1",<br /> array( 'id' => "363", 'name' => "叶子1", 'type' => "2", 'playurl' => "http://XXXXXXX363"),<br /> ),<br /> array( 'id' => "0c5ce42f-ba31-4b7a-8173-79ecae4a73ca", 'name' => "部门2", 'type' => "1",<br /> array( 'id' => "241", 'name' => "叶子1", 'type' => "2", 'playurl' => "http://xxxxx=241"),<br /> array( 'id' => "356", 'name' => "叶子1", 'type' => "2", 'playurl' => "xxxxxxxxx=356"),<br /> ),<br /> )<br /> );<br /> $xml = simplexml_load_string('<nodes/>');<br /> arrayToXml($ar, $xml);<br /> echo $xml->asXML();<br /> <br /> function arrayToXml($ar, $xml) {<br /> foreach($ar as $k=>$v) {<br /> if(is_array($v)) arrayToXml($v, $xml->addChild('node'));<br /> else $xml->addAttribute($k, $v);<br /> }<br /> }<br />