2

I'm working with various XML inputs and outputs and simply want to grab the keys and values like you can with an array.

Is there a simple function that can convert xml to an array or access the keys and values or am I going about this completely the wrong way?

<?php
$xmlstr = "
<key>
    <parent1>
        <child1>val1</child1>
        <child2>val2</child2>
    </parent1>
    <parent2>val4</parent2>
    <parent3>
        <child1 var="1">
            <gchild>
                <child>value</child>
                <child>value</child>
                <parent>
                    <child>value</child>
                </parent>
            </gchild>
        </child1>
    </parent3>
</key>";

$xml = new SimpleXMLElement($xmlstr);
$xmlarray= convertXMLtoArray($xml);

echo $xmlarray[0]; //outputs: key
echo $xmlarray['key'][1]; //outputs: parent2 or array(child1->val1, child2->...)
echo $xmlarray['key']['parent1']['child1'][0]; //outputs: val1
?>

1 Answer 1

4

simplexml_load_file

$xml = simplexml_load_file('test.xml');
var_dump($xml);
Sign up to request clarification or add additional context in comments.

1 Comment

Attributes of an element are accessed like array elements. $child1['var']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.