Reputation: 91
So let's say I want to grab the first h2 element. I was under the impression from googling that something like
$xpath->query('(//h2)[1]');
should work, but that still returns a DOMNodeList instead of a node. So what's going wrong here?
Upvotes: 1
Views: 1209
Reputation: 197767
but that [
$xpath->query('(//h2)[1]');
] still returns a DOMNodeList instead of a node. So what's going wrong here?
The DOMXpath::query()
method always returns a DOMNodeList
if the xpath expression use is syntactically correct. It will never return a single DOMNode
element.
So this is not a still but just an is. So you need to access the first element of that nodelist via the item()
method (it's zero-indexed in difference to the one-index in the xpath predicate):
$h2 = $xpath->query('(//h2)[1]')->item(0);
Take care here, that the query
method will return FALSE
if the xpath expression is invalid which then results in a fatal error here. So sometimes you need to verify the return value first (e.g. if you dynamically create the xpath expression).
If you in the end only want to get the text-content (string-value) of that h2 element, you can alternatively use the DOMXpath::evaluate()
method. Per the xpath string()
function will get the text value of the first node in the set or just an empty string:
$h2Text = $xpath->evaluate('string(//h2)');
I hope this is helpful.
Upvotes: 2