使用 xpath 从数组中获取元素
我有以下 SimpleXML 对象:
SimpleXMLElement Object
(
[@attributes] => Array
(
[status] => ok
)
[a] => SimpleXMLElement Object
(
[b] => Array
(
[0] => SimpleXMLElement Object
(
[c] => Google
[d] => GOOG
[e] => http://www.google.com
)
[1] => SimpleXMLElement Object
(
[c] => Yahoo
[d] => YHOO
[e] => http://www.yahoo.com
)
[2] => SimpleXMLElement Object
(
[c] => Microsoft
[d] => MSFT
[e] => http://www.microsoft.com
)
给定 d
我想得到 e
- 由于 b
是一个数组,有没有什么方法可以做到这一点而不需要循环遍历整个数组?
<stk status="ok">
<a>
<b>
<c>Yahoo</c>
<d>YHOO</d>
<e>http://www.yahoo.com</e>
</b>
<b>
<c>Google</c>
<d>GOOG</d>
<e>http://www.google.com</e>
</b>
<b>
<c>Microsoft</c>
<d>MSFT</d>
<e>http://www.microsoft.com</e>
</b>
</a>
</stk>
I have the following SimpleXML object:
SimpleXMLElement Object
(
[@attributes] => Array
(
[status] => ok
)
[a] => SimpleXMLElement Object
(
[b] => Array
(
[0] => SimpleXMLElement Object
(
[c] => Google
[d] => GOOG
[e] => http://www.google.com
)
[1] => SimpleXMLElement Object
(
[c] => Yahoo
[d] => YHOO
[e] => http://www.yahoo.com
)
[2] => SimpleXMLElement Object
(
[c] => Microsoft
[d] => MSFT
[e] => http://www.microsoft.com
)
Given d
I want to get e
- Since b
is an array, is there any way to do this without looping through the entire array?
<stk status="ok">
<a>
<b>
<c>Yahoo</c>
<d>YHOO</d>
<e>http://www.yahoo.com</e>
</b>
<b>
<c>Google</c>
<d>GOOG</d>
<e>http://www.google.com</e>
</b>
<b>
<c>Microsoft</c>
<d>MSFT</d>
<e>http://www.microsoft.com</e>
</b>
</a>
</stk>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 XPath 查询来询问
e
元素,这些元素是b
元素的子元素,而d
元素的文本为YHOO.
请记住,
SimpleXMLElement::xpath()
将返回一个元素数组,即使 XPath 只找到一个:因此$urls[0]
获取第一个(唯一)一。You could use an XPath query asking for the
e
elements that are children ofb
elements havingd
elements with the textYHOO
.Remember that
SimpleXMLElement::xpath()
will return an array of elements, even if the XPath only finds one: hence$urls[0]
to get the first (only) one.迭代所有
//d
。对于每一个,评估
follow-sibling::e[1]
。我想这就是 Marc B 的意思。
Iterate over all
//d
.For each one, evaluate
following-sibling::e[1]
.I think that's what Marc B meant.