0
AI具有包含属性和值的XML。我想将它转换为数组或数组对象以及属性和值。将PHP XML转换为具有属性和值的数组/对象
XML
<?xml version="1.0" encoding="UTF-8"?>
<itemBody>
<div label="options">
<optionchoices optionIdentifier="RESPONSE" shuffle="false" maxOptions="1">
<choice identifier="A1"><![CDATA[aaaa]]></choice>
<choice identifier="A2"><![CDATA[bbbb]]></choice>
<choice identifier="A3"><![CDATA[cccc]]></choice>
</optionchoices>
</div>
</itemBody>
我尝试了两种一套代码,但不符合预期的结果。
代码1
<?php
$xml = simplexml_load_file('test.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";print_r($xml);echo "</pre>"; exit;
?>
输出
SimpleXMLElement Object
(
[div] => SimpleXMLElement Object
(
[@attributes] => Array
(
[label] => options
)
[optionchoices] => SimpleXMLElement Object
(
[@attributes] => Array
(
[optionIdentifier] => RESPONSE
[shuffle] => false
[maxOptions] => 1
)
[choice] => Array
(
[0] => aaaa
[1] => bbbb
[2] => cccc
)
)
)
)
在上面的输出,如果我们再为您在选择的节点,我们得到值仅而不是属性
XML的代码2
<?php
$xml = simplexml_load_file('test.xml');
echo "<pre>";print_r($xml);echo "</pre>"; exit;
?>
输出
SimpleXMLElement Object
(
[div] => SimpleXMLElement Object
(
[@attributes] => Array
(
[label] => options
)
[optionchoices] => SimpleXMLElement Object
(
[@attributes] => Array
(
[optionIdentifier] => RESPONSE
[shuffle] => false
[maxOptions] => 1
)
[choice] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[identifier] => A1
)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[identifier] => A2
)
)
[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[identifier] => A3
)
)
)
)
)
)
在此输出中,我们只得到属性。
现在我想要的是获取属性以及XML的值。
请帮忙。
在此先感谢。
用循环做。首先循环第一个xml数组,使用选择id作为索引,名称将作为第二个索引,然后在相应的索引中循环第二个输出添加属性.. – 2014-08-27 08:20:16
'$ xml-> div-> attributes()'为第一个?根据需要使用循环。 – Debflav 2014-08-27 08:22:03
这里有几种用于XML序列化,JsonML,BadgerFish,Rayfish的JSON格式......你想创建什么样的目标格式? – ThW 2014-08-27 08:29:35