2015-09-04 30 views
1

我有這樣的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類裏面不知道有多少人在所需的班級內,有多少人在外面?謝謝。

回答

1

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

相關問題