访问 SimpleXMLElement 对象的某些属性 [英] Accessing certain properties of a SimpleXMLElement Object
问题描述
当我 print_r()
变量 $xmlObject
引用的 SimpleXMLElement 对象时,我看到以下结构:
When I print_r()
the SimpleXMLElement Object referenced by variable $xmlObject
, I see the following structure:
SimpleXMLElement Object
(
[@attributes] => Array
(
[uri] => /example
)
[result] => SimpleXMLElement Object
(
[message] => Record(s) added successfully
[recorddetail] => Array
(
[0] => SimpleXMLElement Object
...
)
)
)
注意 $xmlObject->result->message
属性看起来像一个字符串.但是,如果我执行 print_r($xmlObject->result->message)
,我会得到以下结果:
Notice how the $xmlObject->result->message
property looks like it is just a string. However, if I do print_r($xmlObject->result->message)
, I get the following:
SimpleXMLElement Object
(
[0] => Record(s) added successfully
)
所以在这一点上我很困惑.为什么在这种情况下 $xmlObject->result->message
被标识为 SimpleXMLElement Object
的实例,当打印完整的 $xmlObject 的结果时
不建议这样做吗?
So at this point I'm confused. Why is $xmlObject->result->message
being identified as an instance of SimpleXMLElement Object
in this case, when the result of printing the full $xmlObject
doesn't suggest this?
我如何实际访问这个值?我试过 $xmlObject->result->message[0]
,但它只是打印出同样的东西(即我发布的最后一个代码片段).
And how do I actually access this value? I've tried $xmlObject->result->message[0]
, but it just prints out the same thing (i.e. the last code snippet I posted).
推荐答案
在 SimpleXMLElement
上使用 print_r
或 var_dump
时得到的表示与它的内部结构关系不大.例如,没有您可以使用 $element['@attributes']['uri']
访问的属性 @attributes
.你只要做 $element['uri']
The representation you get when using print_r
or var_dump
on a SimpleXMLElement
has very little to do with how it is structured internally. For instance there is no property @attributes
you could access with $element['@attributes']['uri']
either. You just do $element['uri']
事情就是这样.SimpleXmlElement
对象的行为不同.在使用 SimpleXml 之前,请务必阅读 PHP 手册中的示例:
This is simply the way it is. SimpleXmlElement
objects behave different. Make sure you read the examples in the PHP Manual before using SimpleXml:
要详细了解它的实现,您必须查看源代码:
To understand the implementation it in detail, you'd have to look at the source code:
要打印$xmlObject->result->message
,您只需执行echo $xmlObject->result->message
.这会将 SimpleXmlElement
自动转换为字符串.
To print $xmlObject->result->message
you just do echo $xmlObject->result->message
. That will autocast the SimpleXmlElement
to string.
这篇关于访问 SimpleXMLElement 对象的某些属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!