PHP XML到具有属性和值的数组/对象 [英] PHP XML to Array/Object with Attributes and Values
问题描述
AI有一个XML,其中包含属性和值.我想将其与属性和值一起转换为Array或Array Object.
AI have an XML which have attributes as well as values in them. I want to convert it to an Array or Array Object along with attributes and values.
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>
我尝试了两套代码,但结果与预期不符.
I tried two set of code but the result was not as expected.
代码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
)
)
)
)
在上面的输出中,如果我们检查然后在选择节点中,则仅获得值,而不是属性
In the above output if we check then in choice node we get the values only and not the attributes
代码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的属性.
In this output we get only attributes of XML.
现在我要获取的是XML的属性和值.
Now what I want is to obtain Attributes as well as Values of the XML.
请帮助.
谢谢.
推荐答案
这就是我得到的.这就是我所期望的解决方案.
This is what I got. And this is the solution which I expected.
http://outlandish.com/blog/xml-to-json/
这篇关于PHP XML到具有属性和值的数组/对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!