gpt4 book ai didi

php - 如何使用 DOMDocument 类删除 HTML 元素

转载 作者:可可西里 更新时间:2023-10-31 22:06:21 25 4
gpt4 key购买 nike

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

最佳答案

除了 Dave Morgan 的回答之外,您还可以使用 DOMNode::removeChild 从 child 列表中删除 child :

通过标签名称删除子项

//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();

}

按类(class)名称删除 child

//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

How to delete element with DOMDocument?

How to get full HTML from DOMXPath::query() method?

关于php - 如何使用 DOMDocument 类删除 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1171597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com