请教大神数组转XML格式问题

WBOY
Release: 2016-06-23 14:26:32
Original
847 people have browsed it

本帖最后由 HUENKE 于 2013-11-04 17:51:55 编辑



我PHP存储的内容为树状递归的数组key=>value这种
转为XML为上图格式
但是
我需要如下格式的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>
Copy after login


	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文件	}
Copy after login


回复讨论(解决方案)

$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);  }}
Copy after login

战略性mark

我的ARRAY格式为

输出格式为

貌似多了一层NODE怎么解决

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!