在php中获取'DomNode'类型对象

时间:2011-10-18 16:42:44

标签: php domdocument

我使用php的DomDocument类加载HTML文件,然后清空其内容。问题是,当我执行.removeChild()时,它给了我'Not Found Error'。继承我的代码

$doc=new DOMDocument();
$doc->loadHTMLFile("a.html");
$body= $doc->getElementsByTagName('body')->item(0);
foreach($body->childNodes as $child)
{
        $body->removeChild($child);

} 

$ child是DOMText类型....可能是因为removeChild需要DOMNode而不是DOMText?如果是,那么我如何迭代childNodes,使$ child的类型为DOMNode?

1 个答案:

答案 0 :(得分:0)

使用for循环而不是foreach循环。

$doc=new DOMDocument();
$doc->loadHTML("c.html");
$doc->preserveWhiteSpace = true;
$body = $doc->getElementsByTagName('body')->item(0);
$children = $body->childNodes;
$length = $children->length;
for($i = 0 ; $i < $length; $i++) {
    $child = $children->item($i);
    if ($child)
        $body->removeChild($child);
}
$html = $doc->saveHTML();
echo $html;