获得';DomNode';php中的类型对象

获得';DomNode';php中的类型对象,php,domdocument,Php,Domdocument,我使用php的DomDocument类加载HTML文件,然后清空其内容。问题是当我这样做时。removeChild()会给我“找不到错误”。这是我的密码 $doc=new DOMDocument(); $doc->loadHTMLFile("a.html"); $body= $doc->getElementsByTagName('body')->item(0); foreach($body->childNodes as $child) { $body-&g

我使用php的DomDocument类加载HTML文件,然后清空其内容。问题是当我这样做时。removeChild()会给我“找不到错误”。这是我的密码

$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?

使用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;
$doc=newDOMDocument();
$doc->loadHTML(“c.html”);
$doc->preserveewhitespace=true;
$body=$doc->getElementsByTagName('body')->item(0);
$children=$body->childNodes;
$length=$children->length;
对于($i=0;$i<$length;$i++){
$child=$children->item($i);
if(儿童)
$body->removeChild($child);
}
$html=$doc->saveHTML();
echo$html;