user6618536 user6618536 - 3 months ago 12
PHP Question

PHP simplexml reading child tag attribute

I have a xml like below,

<y>
<n>
<n id='test1'></n>
<n id='test2'></n>
</n>
</y>


and want to read each "id" of child "n" tag .

I use this php code;

$xml = simplexml_load_file("my.xml");
echo $xml->n[0]->n;


but getting error,


Trying to get property of non-object

Answer

It should be : $xml->n->n[0] which is an array. If you print_r($xml) you might see like this:

SimpleXMLElement Object
(
    [n] => SimpleXMLElement Object
    (
        [n] => Array
            (
                [0] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => test1
                            )

                    )

                [1] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => test2
                            )

                    )

            )

    )

)
Comments