I'm using the PHP DOM to extract data from a page and having a hard time getting the href value for a nested element using DomXPath.
Here's my html:
<span class="myclass">
<a href="/relative/path">My Value</a>
<span class="otherclass"></span>
</span>
And here's my XPath query:
$xpath = new DomXPath($dom);
$classname = "myclass";
$nodes = $xpath->query("//span[contains(@class, '$classname')]");
foreach ($nodes as $node){
echo $node->nodeValue;
echo ",";
echo $node->getAttribute('href');
echo "<br>";
}
I'm able to get the nodeValue just fine ('My Value'), but not the value of the href. I'm sure I'm missing something and not understanding this. Do I need a separate query to get the href value? What's the best way to do this?
In your loop, $node
is the span because your XPath is selecting span elements with the given class, that's why it doesn't have a href
.
If you want to select the anchor that is under the span, change to:
$nodes = $xpath->query("//span[contains(@class, '$classname')]/a");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.