我正在查看以下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';
我的结果空洞了。知道为什么吗?
答案 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;
}