trouble in removing the meta tag using php DOM api

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

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


           foreach($meta as $old         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-24 13:15

    You're looping over the array and removing from it at the same time.

    Unfortunately, this means that every time you remove a child inside the loop, the next loop iteration skips a node. foreach is not "clever enough" in conjunction with DOMDocument to do this intelligently.

    Instead of foreach, use indexes:

    $meta = $html->getElementsByTagName("meta");
    for ($i = $meta->length - 1; $i >= 0; $i--) { // `foreach` breaks the `removeChild`
       $child = $meta->item($i);
       $child->parentNode->removeChild($child);
    }
    

提交回复
热议问题