Home > Backend Development > PHP Tutorial > 请问大神数组转XML格式有关问题

请问大神数组转XML格式有关问题

WBOY
Release: 2016-06-13 11:39:24
Original
749 people have browsed it

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

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

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


<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 />
Copy after login

Related labels:
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