PHP DomXPath查找嵌套元素值

PHP DomXPath查找嵌套元素值,php,dom,xpath,Php,Dom,Xpath,我正在使用PHPDOM从页面中提取数据,并且很难使用DomXPath获取嵌套元素的href值 这是我的html: <span class="myclass"> <a href="/relative/path">My Value</a> <span class="otherclass"></span> </span> 下面是我的XPath查询: $xpath = new DomXPath($dom); $

我正在使用PHPDOM从页面中提取数据,并且很难使用DomXPath获取嵌套元素的href值

这是我的html:

<span class="myclass">
    <a href="/relative/path">My Value</a>
    <span class="otherclass"></span>
</span>

下面是我的XPath查询:

$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>";
}
$xpath=newdomxpath($dom);
$classname=“myclass”;
$nodes=$xpath->query(//span[contains(@class,$classname')]);
foreach($node作为$node){
echo$node->nodeValue;
回声“,”;
echo$node->getAttribute('href');
回声“
”; }

我可以很好地获取nodeValue(“我的值”),但不能获取href的值。我肯定我错过了什么,不明白这一点。我是否需要单独的查询来获取href值?最好的方法是什么?

在循环中,
$node
是span,因为XPath正在使用给定的类选择span元素,所以它没有
href

如果要选择跨度下的锚点,请更改为:

$nodes = $xpath->query("//span[contains(@class, '$classname')]/a");