我正在通过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
我无法跳过它
请告诉我任何可能的方法,我可以区分DOMText
和DOMElement
的资源类型。
答案 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');
}