Xpath查询辅助嵌套锚点href提取

时间:2013-08-29 16:34:29

标签: php xpath domdocument

这是我的代码:

$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文本。我的查询出了什么问题?

2 个答案:

答案 0 :(得分:2)

可能缺少“@”

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

答案 1 :(得分:0)

XPath不正确。它应该是:

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

然后$nodes将是<a>内所有<div class="cgus_post">个代码的列表,您可以使用

获取其href
foreach($nodes as $node) {
   $href = $node->getAttribute('href');
}
相关问题