remove comments from html source code

前端 未结 5 484
深忆病人
深忆病人 2020-12-20 13:13

I know how to get the html source code via cUrl, but I want to remove the comments on the html document (I mean what is between ). In addition,

5条回答
  •  离开以前
    2020-12-20 13:58

    I've run in to issues modifying a DOMNodeList in a foreach loop which went away went I iterated backwards through the list. For that reason, I'd would not recommend a foreach loop as in the accepted answer. Instead use a for loop like this:

    $dom = new DOMDocument();
    $dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    for ($els = $xpath->query('//comment()'), $i = $els->length - 1; $i >= 0; $i--) {
        $els->item($i)->parentNode->removeChild($els->item($i));
    }
    

提交回复
热议问题