[英]PHP DomXPath to find nested element value
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. 我正在使用PHP DOM从页面中提取数据,并且很难使用DomXPath获取嵌套元素的href值。
Here's my html: 这是我的html:
<span class="myclass">
<a href="/relative/path">My Value</a>
<span class="otherclass"></span>
</span>
And here's my XPath query: 这是我的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>";
}
I'm able to get the nodeValue just fine ('My Value'), but not the value of the href. 我能够很好地获得nodeValue(“我的价值”),但不能获得href的价值。 I'm sure I'm missing something and not understanding this.
我确定我遗漏了一些东西并且对此不了解。 Do I need a separate query to get the href value?
我是否需要单独的查询来获取href值? 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
. 在循环中,
$node
是span,因为XPath正在选择具有给定类的span元素,这就是为什么它没有href
。
If you want to select the anchor that is under the span, change to: 如果要选择跨度下的锚,请更改为:
$nodes = $xpath->query("//span[contains(@class, '$classname')]/a");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.