DOM XPath Selector没有抓取类

时间:2013-08-26 22:13:30

标签: php dom xpath domdocument

我正在查看以下stackoverflow问题:Getting Dom Elements By Class name并且它引用了我可以使用此代码获取类名:

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'someclass someclass2';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
print "<pre>".print_r($nodes,true)."</pre>";

我也尝试将$classname更改为只有一个类:

$classname = 'someclass2';

我的结果空洞了。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

您必须循环搜索结果,因为print_r()不会打印DOMNodeList的成员。像这样:

$text = '<html><body><div class="someclass someclass2">sometext</div></body></html>';
$dom = new DomDocument();
$dom->loadHTML($text);
$classname = 'someclass someclass2';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

// iterate through the result. print_r will not suffer
foreach($nodes as $node) {
    echo $node->nodeValue;
}