我正在按 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
的资源类型。
最佳答案
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');
}
关于php - 如何区分 domText 和 domElement 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330516/