0

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!

1
  • 1
    You don't need to use print_r(), I ran your code just fine with echo instead. Commented Nov 18, 2014 at 19:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.