如何使用DOMDocument类删除HTML元素

Rol*_*and 11 php domdocument

有没有办法通过使用DOMDocument类删除HTML元素?

Raf*_*shi 20

除了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();

}
Run Code Online (Sandbox Code Playgroud)

按类名删除子项

//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();
}   
Run Code Online (Sandbox Code Playgroud)

资源

http://us2.php.net/manual/en/domnode.removechild.php

如何用DOMDocument删除元素?

如何从DOMXPath :: query()方法获取完整的HTML?


Dav*_*gan 13

http://us2.php.net/manual/en/domnode.removechild.php

DomDocument是一个DomNode ..你可以打电话给删除孩子,你应该没事.

编辑:刚刚注意到你可能正在谈论你目前正在使用的页面.不知道DomDocument是否有效.您可能希望在那时使用javascript(如果它已经被提供给客户端)