PHP XML to Array with Attributes and Values

Discussion in 'PHP' started by abhicyco, Aug 27, 2014.

  1. #1
    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="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.

    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] => A1
    )
    )
    [1] => SimpleXMLElement Object
    (
    [@attributes] => Array
    (
    [identifier] => A2
    )
    )
    [2] => SimpleXMLElement Object
    (
    [@attributes] => Array
    (
    [identifier] => A3
    )
    )
    )
    )
    )
    )

    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.
     
    Last edited: Aug 27, 2014
    abhicyco, Aug 27, 2014 IP
  2. abhicyco

    abhicyco Active Member

    Messages:
    36
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #2
    Thanks to all those who checked out this topic and either trying for solution or left it as it is.

    I got a solution for this and this is what I expected.

    http://outlandish.com/blog/xml-to-json/
     
    abhicyco, Aug 27, 2014 IP