开发者

php simple xml element question/bug

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?


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.


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.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜