简单的HTML DOM解析器 - 找到另一个类
问题描述:
我有这样的HTML脚本内部类:简单的HTML DOM解析器 - 找到另一个类
<div class="find-this">I do not need this</div>
<div class="content">
<div class="find-this">I need this</div>
</div>
<div class="content">
<div class="find-this">I need this</div>
<div class="find-this">I need this as well</div>
</div>
到目前为止,我有这样的:
foreach($html->find('div[class=content]') as $key => $element) :
$result = $html->find('div[class=find-this]', $key)->innertext;
echo $result;
endforeach;
如何找到find-this
类里面不知道有多少人在所需的班级内,有多少人在外面?谢谢。
答
XPath可能是你正在寻找的。通过这个代码,你只能得到你需要的三个节点。
/* Creates a new DomDocument object */
$dom = new DomDocument;
/* Load the HTML */
$dom->loadHTMLFile("test.html");
/* Create a new XPath object */
$xpath = new DomXPath($dom);
/* Query all <divs> with the class name */
$nodes = $xpath->query("//div[@class='content']//div[@class='find-this']");
/* Set HTTP response header to plain text for debugging output */
header("Content-type: text/plain");
/* Traverse the DOMNodeList object to output each DomNode's nodeValue */
foreach ($nodes as $i => $node) {
echo "Node($i): ", $node->nodeValue, "\n";
}
注:我根据我的回答this other related answer。