Reputation: 23959
I have the following which prints 100
- which is correct - however, I have to use print_r()
which is obviously wrong
$dom = new DOMDocument();
$dom->loadHTML('<span class="foo" id="bar" itemprop="price">100</span>');
$xpath = new DOMXPath($dom);
$results = $xpath->evaluate('number(//*[@itemprop="price"])');
print_r($results);`
So, how should I get the single result which is 100? I've tried $results[0]
which didn't work.
Am sure it's simple but beating me!
Upvotes: 0
Views: 102
Reputation: 25935
Use the ->item()
method on the result to access the DOM nodes that your XPath query returns. Also you should rather use the query()
method when you want to run an XPath query. I've never really understood the purpose of using evaluate()
.
$xpath = new DOMXPath($dom);
$results = $xpath->query('//*[@itemprop="price"]');
echo $results->item(0)->nodeValue;
DOMXPath->query() returns an instance of DOMNodeList
which you can iterate on with foreach()
or access a specific result item by using the ->item()
method. Its only argument is the 0-based index into the returned list.
Upvotes: 1