2012-07-04 80 views
2

我正在通過DOM對象遍歷一個頁面,並陷入了一個點。如何區分domText和domElement對象?

這裏的HTML代碼示例我必須遍歷..

... 
<div class="some_class"> 
some Text Some Text 
<div class="childDiv"> 
</div> 
<div class="childDiv"> 
</div> 
<div class="childDiv"> 
</div> 
<div class="childDiv"> 
</div> 
</div> 
... 

現在,這裏的部分代碼..

$dom->loadHTML("content above"); 

// I want only first level child of this element. 
$divs = $dom->childNodes; 
foreach ($divs as $div) 
{ 
    // here the problem starts - the first node encountered is DomTEXT 
    // so how am i supposed to skip that and move to the other node. 

    $childDiv = $div->getElementsByTagName('div'); 
} 

正如你可以看到.. $childNodes回報DOMNodeList,然後我如果在任何時候遇到DOMText,我無法跳過它。

請讓我知道任何可能的方式,我可以把一個條件區分資源類型DOMTextDOMElement

+0

http://php.net/instanceof http://php.net/domdocument.getElementsByTagName – hakre

回答

5
foreach($divs as $div){ 

    if($div->nodeType !== 1) { //Element nodes are of nodeType 1. Text 3. Comments 8. etc rtm 
     continue; 
    } 

    $childDiv = $div->getElementsByTagName('div'); 
} 
+0

謝謝。有效。! –

+0

'getElementsByTagName'接受*任何*標記的*。那麼不需要在foreach裏面過濾。 – hakre