如何区分domText和domElement对象?

时间:2012-07-04 13:55:52

标签: php dom domdocument

我正在通过DOM对象遍历页面并陷入困境。

以下是我必须迭代的示例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,然后我按foreach进行迭代,如果在任何时候遇到DOMText我无法跳过它

请告诉我任何可能的方法,我可以区分DOMTextDOMElement的资源类型。

1 个答案:

答案 0 :(得分:6)

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');
}