PHP XML to Array/Object with Attributes and Values



I 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="QUE_3624_C1"><![CDATA[aaaa]]></choice>
<choice identifier="QUE_3624_C2"><![CDATA[bbbb]]></choice>
<choice identifier="QUE_3624_C3"><![CDATA[cccc]]></choice>
</optionchoices>
</div>
</itemBody>


I tried two set of code but the result was not as expected.


Code 1



<?php
$xml = simplexml_load_file('test.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";print_r($xml);echo "</pre>"; exit;
?>


Output



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


Code 2



<?php
$xml = simplexml_load_file('test.xml');
echo "<pre>";print_r($xml);echo "</pre>"; exit;
?>


Output



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] => QUE_3624_C1
)

)

[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[identifier] => QUE_3624_C2
)

)

[2] => SimpleXMLElement Object
(
[@attributes] => Array
(
[identifier] => QUE_3624_C3
)

)

)

)

)

)


In this output we get only attributes of XML.


Now what I want is to obtain Attributes as well as Values of the XML.


Please help.


Thanks in advance.


No comments:

Post a Comment