Why does SimpleXML change my array to the array's first element when I use it?

Viewed 4668

Here is my code:

$string = <<<XML
<?xml version='1.0'?> 
<test>
 <testing>
  <lol>hello</lol>
  <lol>there</lol>
 </testing>
</test>
XML;
$xml = simplexml_load_string($string);
echo "All of the XML:\n";
print_r $xml;
echo "\n\nJust the 'lol' array:";
print_r $xml->testing->lol;

Output:

All of the XML:

SimpleXMLElement Object
(
    [testing] => SimpleXMLElement Object
        (
            [lol] => Array
                (
                    [0] => hello
                    [1] => there
                )

        )

)




Just the 'lol' array:

SimpleXMLElement Object
(
    [0] => hello
)

Why does it output only the [0] instead of the whole array? I dont get it.

5 Answers

What @Yottatron suggested is true, but not at all the cases as this example shows :

if your XML would be like this:

<?xml version='1.0'?>
<testing>
    <lol>
        <lolelem>Lol1</lolelem>
        <lolelem>Lol2</lolelem>
        <notlol>NotLol1</lolelem>
        <notlol>NotLol1</lolelem>
    </lol>
</testing>

Simplexml's output would be:

SimpleXMLElement Object
(
[lol] => SimpleXMLElement Object
    (
        [lolelem] => Array
            (
                [0] => Lol1
                [1] => Lol2
            )

        [notlol] => Array
            (
                [0] => NotLol1
                [1] => NotLol1
            )

    )

)

and by writing

$xml->lol->lolelem

you'd expect your result to be

Array
(
     [0] => Lol1
     [1] => Lol2
)

but instead of it, you would get :

SimpleXMLElement Object 
(
    [0] => Lol1
)

and by

$xml->lol->children()

you would get:

SimpleXMLElement Object
(
[lolelem] => Array
    (
        [0] => Lol1
        [1] => Lol2
    )

[notlol] => Array
    (
        [0] => NotLol1
        [1] => NotLol1
    )

)

What you need to do if you want only the lolelem's:

$xml->xpath("//lol/lolelem")

That gives this result (not as expected shape but contains the right elements)

Array
(
    [0] => SimpleXMLElement Object
    (
        [0] => Lol1
    )

    [1] => SimpleXMLElement Object
    (
        [0] => Lol2
    )

)
Related