php 简单 xml 元素问题/bug
我有一些 xml,可以说
当我运行以下命令时:
$simpleXMLElement = new SimpleXMLElement($xml);
pr($simpleXMLElement);
我得到以下内容:
SimpleXMLElement Object
(
[@attributes] => Array
(
[number] => 12
)
[0] =>
)
它抛出 0 条目。这很奇怪。我不知道它应该代表什么。如果我这样做:
<names number="12"><name first="oliver" /></names>
我会得到以下输出:
SimpleXMLElement Object
(
[@attributes] => Array
(
[number] => 12
)
[name] => SimpleXMLElement Object
(
[@attributes] => Array
(
[first] => oliver
)
)
)
这是预期的(至少对我来说)。有什么想法/方向吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先:如果您的帖子格式不正确,则不会显示 XML。任何代码缩进至少 4 个空格。
其次,不要期望
print_r()
或var_dump()
为您提供SimpleXMLElement
的精确表示,因为 SimpleXML 使用了很多魔法,所以子项和属性不一定会出现在输出中。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()
orvar_dump()
to give you an exact representation of aSimpleXMLElement
because SimpleXML uses lots of magic, so children and attributes won't necessarily show up in the output.这似乎只是 SimpleXML 做了一个快速而肮脏的解析元素的工作:因为你有
,所以它在元素内添加了一个数组,就像期望的元素一样在其中,当它在names
标记内找不到任何元素时,它会留下一个空数组,其中包含键0
,因为它不知道名称是什么给它。短标签 (
) 不应生成空内容。 (听起来很奇怪。)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 thenames
tags, it leaves an empty array, with the key0
, 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.)