trouble in removing the meta tag using php DOM api

后端 未结 2 1024
暗喜
暗喜 2021-01-24 12:39
$html = new DOMDocument();
           $html->loadHTMLFile($filename);

           $meta = $html->getElementsByTagName(\"meta\");


           foreach($meta as $old         


        
2条回答
  •  清歌不尽
    2021-01-24 13:03

    When you use foreach to iterate over the DOMNodeList and remove an element, you are changing the DOMNodeList content, so nodes will be skipped. You have to iterate backwards:

    $nodes = $dom->getElementsByTagName('meta');
    for ($i = $nodes->length - 1; $i >= 0; $i--) {
        $nodes->item($i)->parentNode->removeChild($nodes->item($i));
    }
    

提交回复
热议问题