5

我正在按 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遇到 a 我都无法跳过它。

请让我知道任何可能的方式,我可以提出条件区分资源类型DOMTextDOMElement

4

1 回答 1

9
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');
}
于 2012-07-04T14:03:40.757 回答