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