php 如何使用 DOMDocument 删除元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15272726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:57:10  来源:igfitidea点击:

How to delete element with DOMDocument?

phpdomdocument

提问by Kin

Is it possible to delete element from loaded DOMwithout creating a new one? For example something like this:

是否可以在DOM不创建新元素的情况下从加载中删除元素?例如这样的事情:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('a') as $href)
    if($href->nodeValue == 'First')
        //delete

回答by hakre

You remove the node by telling the parent node to remove the child:

您可以通过告诉父节点删除子节点来删除节点:

$href->parentNode->removeChild($href);

See DOMNode::$parentNodeDocsand DOMNode::removeChild()Docs.

请参阅DOMNode::$parentNode文档DOMNode::removeChild()文档

See as well:

另见:

回答by alexanderbird

This took me a while to figure out, so here's some clarification:

这花了我一段时间才弄明白,所以这里有一些澄清:

If you're deleting elements from within a loop (as in the OP's example), you need to loop backwards

如果要从循环中删除元素(如 OP 的示例中所示),则需要向后循环

$elements = $completePage->getElementsByTagName('a');
for ($i = $elements->length; --$i >= 0; ) {
  $href = $elements->item($i);
  $href->parentNode->removeChild($href);
}

DOMNodeList documentation: You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards

DOMNodeList 文档:如果向后迭代,您可以修改甚至删除 DOMNodeList 中的节点

回答by silkfire

Easily:

容易地:

$href->parentNode->removeChild($href);

回答by PM7Temp

I know this has already been answered but I wanted to add to it.

我知道这已经得到了回答,但我想补充一下。

In case someone faces the same problem I have faced.

如果有人遇到我遇到的同样问题。

Looping through the domnode list and removing items directly can cause issues.

循环遍历 domnode 列表并直接删除项目可能会导致问题。

I just read this and based on that I created a method in my own code base which works:https://www.php.net/manual/en/domnode.removechild.php

我刚刚阅读了这篇文章,并基于此在我自己的代码库中创建了一个有效的方法:https: //www.php.net/manual/en/domnode.removechild.php

Here is what I would do:

这是我会做的:

$links = $dom->getElementsByTagName('a');
$links_to_remove = [];

foreach($links as $link){
    $links_to_remove[] = $link;
}

foreach($links_to_remove as $link){
    $link->parentNode->removeChild($link);
}

$dom->saveHTML();