views:

55

answers:

2

Hey there,

I have some xml, lets say <names number="12"></names>

When I run the following:

$simpleXMLElement = new SimpleXMLElement($xml);
pr($simpleXMLElement);

I get the following:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [number] => 12
        )

    [0] => 

)

It throws in that 0 entry. This is weird. I don't know what it's supposed to represent. If I do this instead:

<names number="12"><name first="oliver" /></names>

I get the following output:

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [number] => 12
        )

    [name] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [first] => oliver
                )

        )

)

This is as expected (for me at least). Any thoughts/direction?

A: 

First: if you don't correctly format your post, the XML will not be displayed. Indent any code with at least 4 spaces.

Secondly, do not expect print_r() or var_dump() to give you an exact representation of a SimpleXMLElement because SimpleXML uses lots of magic, so children and attributes won't necessarily show up in the output.

Josh Davis
A: 

It seems to be just SimpleXML doing a quick-and-dirty job of parsing the element: Since you have <names></names>, it adds an array inside the element, as expecting elements within it, and when it doesn't find any elements inside the names tags, it leaves an empty array, with the key 0, since it doesn't know what name to give it.

A short tag (<names />) shouldn't generate the empty content. (As weird as that sounds.)

Tordek