php - 如何区分 domText 和 domElement 对象?

标签 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 的资源类型。

最佳答案

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/

相关文章:

php - 如果来自数据库的散列密码与输入密码匹配,则登录

PHP mySQL 获取表头函数

javascript - Mootools:遍历 this.getParent() x 次到特定元素

android - Android 3.0及以上版本无法从res中获取xml数据

PHP:错误检查中的错误

php - 使用 XPath 从 XML 文档中提取特定于标签的数据

php - 是否可以通过 Paypal 自定义字段发送多个 ID?

php - 无法访问在 cpanel 中创建的文件夹

c++ - gSOAP DOM 解析器问题

php - 如何使用 php 在 html 中的特定元素之后插入新元素?