【发布时间】:2009-07-23 13:10:46
【问题描述】:
有没有办法通过使用 DOMDocument 类来删除 HTML 元素?
【问题讨论】:
标签: php domdocument
有没有办法通过使用 DOMDocument 类来删除 HTML 元素?
【问题讨论】:
标签: php domdocument
除了 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
【讨论】:
http://us2.php.net/manual/en/domnode.removechild.php
DomDocument 是一个 DomNode.. 你可以调用 remove child 就可以了。
编辑:刚刚注意到您可能正在谈论您当前正在使用的页面。不知道 DomDocument 是否会起作用。您可能想在那时使用 javascript(如果它已经提供给客户端)
【讨论】: