Get an element from an array using xpath
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
)
开发者_JS百科[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>
You could use an XPath query asking for the e
elements that are children of b
elements having d
elements with the text YHOO
.
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.
$xml = '<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>';
$stk = simplexml_load_string($xml);
$urls = $stk->xpath('/stk/a/b[d="YHOO"]/e');
$yhoo = (string) $urls[0];
echo $yhoo;
Iterate over all //d
.
For each one, evaluate following-sibling::e[1]
.
I think that's what Marc B meant.
精彩评论