Xpath查询帮助嵌套锚href提取



这是我的代码:

$text = '<div class="cgus_post"><a href="?p=15055">Hello</a></div>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'cgus_post';
$finder = new DomXPath($dom);
$nodes = $finder->query('//div[class="cgus_post"]//@href');

我正在尝试获取div cgus_post中的锚链接的href文本。我的查询出了什么问题?

可能缺少"@"

'//div[@class="cgus_post"]//@href'

XPath不正确。应该是:

//div[@class="cgus_post"]/a

然后$nodes将是<div class="cgus_post">中所有<a>标签的列表,您可以使用获得它们的hrefs

foreach($nodes as $node) {
   $href = $node->getAttribute('href');
}

最新更新