有没有办法通过使用DOMDocument类来删除 HTML 元素?
			
			21413 次
		
2 回答
            22        
        
		
除了戴夫摩根的回答,您还可以使用DOMNode::removeChild从孩子列表中删除孩子:
按标签名称删除孩子
//The following example will delete the table element of an HTML content.
$dom = new DOMDocument();
//avoid the whitespace after removing the node
$dom->preserveWhiteSpace = false;
//parse html dom elements
$dom->loadHTML($html_contents);
//get the table from dom
if($table = $dom->getElementsByTagName('table')->item(0)) {
   //remove the node by telling the parent node to remove the child
   $table->parentNode->removeChild($table);
   //save the new document
   echo $dom->saveHTML();
}
按班级名称删除孩子
//same beginning
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html_contents);
//use DomXPath to find the table element with your class name
$xpath = new DomXPath($dom);
$classname='MyTableName';
$xpath_results = $xpath->query("//table[contains(@class, '$classname')]");
//get the first table from XPath results
if($table = $xpath_results->item(0)){
    //remove the node the same way
    $table ->parentNode->removeChild($table);
    echo $dom->saveHTML();
}   
资源
于 2014-12-08T08:35:50.803   回答
    
    
            13        
        
		
http://us2.php.net/manual/en/domnode.removechild.php
DomDocument 是一个 DomNode .. 你可以调用 remove child ,你应该没问题。
编辑:刚刚注意到您可能正在谈论您当前正在使用的页面。不知道 DomDocument 是否会起作用。您可能想在那时使用 javascript(如果它已经提供给客户端)
于 2009-07-23T13:12:54.197   回答