【问题标题】:Recursively loop through the DOM tree and remove unwanted tags?递归循环遍历 DOM 树并删除不需要的标签?
【发布时间】:2011-06-01 13:22:10
【问题描述】:
$tags = array(
    "applet" => 1,  
    "script" => 1
);

$html = file_get_contents("test.html");
$dom = new DOMdocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$body = $xpath->query("//body")->item(0);

我正在循环浏览网页的“正文”并删除 $tags 数组中列出的所有不需要的标签,但我找不到方法。那我该怎么做呢?

【问题讨论】:

    标签: php html dom


    【解决方案1】:

    你考虑过HTML Purifier吗?从你自己的 html 清理开始只是重新发明轮子,而且不容易完成。

    此外,黑名单方法也很糟糕,请参阅SO/why-use-a-whitelist-for-html-sanitizing

    您可能也有兴趣阅读how to cinfigure allowed tags & attributestesting HTML Purifier demo

    【讨论】:

    • 非常感谢您的提示。我将改用白名单。哦,祝大家新年快乐:)
    【解决方案2】:
    $tags = array(
        "applet" => 1,  
        "script" => 1
    );
    
    $html = file_get_contents("test.html");
    $dom = new DOMdocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    
    for($i=0; $i<count($tags); ++$i) {
       $list = $xpath->query("//".$tags[$i]);
       for($j=0; $j<$list->length; ++$j) {
          $node = $list->item($j);
          if ($node == null) continue;
          $node->parentNode->removeChild($node);
       }
    }
    
    $string = $dom->saveXML();
    

    类似的东西。

    【讨论】:

    • 如果没有执行删除,您应该只增加$j。否则你会跳过元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多