有没有办法使用DOMDocument
类删除HTML元素?
答案 0 :(得分:19)
除了Dave Morgan的回答,您还可以使用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();
}
<强>资源强>
http://us2.php.net/manual/en/domnode.removechild.php
答案 1 :(得分:13)
http://us2.php.net/manual/en/domnode.removechild.php
DomDocument是一个DomNode ..你可以调用删除子,你应该没事。
编辑:刚刚注意到你可能正在谈论你目前正在使用的页面。不知道DomDocument是否有效。您可能希望在此时使用javascript(如果已经将其提供给客户端)