relm
relm

Reputation: 291

Trouble getting subsequent Xpath queries to work

I'm trying to access the multiple items across multiple Xpath queries, while using the first query as a base.

I tried:

$playerinfo = $xpath->query('//*[@class="PlayerHeader"]');
$playername = $xpath->query('/h3/a', $playerinfo);
echo $playername->item(0)->nodeValue;

Nothing is returned. If I do

$playerinfo = $xpath->query('//*[@class="PlayerHeader"]/h3/a');
echo $playerinfo->item(0)->nodeValue;

It works fine. Any help is appreciated.

Upvotes: 1

Views: 144

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243619

$playername = $xpath->query('/h3/a', $playerinfo); 

You are trying to evaluate an absolute XPath expression against a node -- that isn't meaningful.

An absolute expression is always evaluated having the document node as context node.

there is no /h3 node (the top element is probably html, not h3, and due to this, there is no /h3/a node also).

Solution: Use a relative expression: h3/a.

Recommendation: Read about "Relative and Absolute XPath expressions" and understand this topic.

Upvotes: 3

Marc B
Marc B

Reputation: 360922

$playerinfo is a list of matching nodes - when you use it as the context for a subsequent search, the context can only be a SINGLE node, not a node list:

$playername = $xpath->query('/h3/a', $playerinfo->item(0));

Upvotes: 1

Related Questions