Reputation: 283
I need some assistance with xpath to extract a value $283 out of an html page.
Here's my PHP
$html = file_get_contents("https://test.com/testpage.php");
$html = tidy_repair_string($html);
$doc = new DomDocument();
$doc->loadHtml($html);
$xpath = new DomXPath($doc);
$avg = $xpath->evaluate('string(//*[@id="Average"]/@value)');
echo $avg;
Here is the HTML
<div class="List">
<span class="bold">Avg</span>
<span id="Average">$283</span>
</div>
Thanks in advance.
Upvotes: 6
Views: 7016
Reputation: 184955
Try this XPath expression :
//div[@class="List"]/span[@id="Average"]
or simply :
//*[@id='Average']
This is a full working code :
<?php
$doc = new DOMDocument();
$doc->loadHTMLFile('http://127.0.0.1/test.html');
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//*[@id='Average']");
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
?>
Just replace URL with your own.
Upvotes: 10