PHP DOMDocument:按类删除元素 [英] PHP DOMDocument: Delete elements by class

查看:104
本文介绍了PHP DOMDocument:按类删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图删除具有给定类的每个节点。

I' trying to delete every node with a given class.

要查找我使用的元素:

$xpath = new DOMXPath($dom);
    foreach( $xpath->query('//div[contains(attribute::class, "foo")]') as $e ) {
        // Delete this node
    }

但是如何删除此foreach循环中的元素?

But how can I delete the elements in this foreach-loop?

编辑::我如何首先检查DOM中是否有一个元素为 foo的元素(在开始循环之前)?

By the way: How can I check first if there is a element with the class "foo" in the DOM (before starting the loop)?

更新:

这是我的HTML:

<div class="main">
    <div class="delete_this" contenteditable="true">Target</div>
    <div class="class1"></div>
    <div class="content"><p>Anything</p></div>
</div>

这不适用于上面的示例:

This doesn't work for the example above:

$xpath = new DOMXPath($dom);
foreach( $xpath->query('//div[contains(attribute::class, "delete_this")]') as $e ) {
    $e->parentNode->removeChild($e);
}


推荐答案

您需要使用<父元素的code> removeChild()方法:

$xpath = new DOMXPath($dom);
foreach($xpath->query('//div[contains(attribute::class, "foo")]') as $e ) {
    // Delete this node
    $e->parentNode->removeChild($e);
}

Btw,关于第二个问题,如果没有找到元素,则循环

Btw, about your second question, if there are no elements found, the loop won't iterate at all.

以下是一个有效的示例:

Here comes a working example:

$html = <<<EOF
<div class="main">
    <div class="delete_this" contenteditable="true">Target</div>
    <div class="class1"></div>
    <div class="content"><p>Anything</p></div>
</div>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($html);

$selector = new DOMXPath($doc);
foreach($selector->query('//div[contains(attribute::class, "delete_this")]') as $e ) {
    $e->parentNode->removeChild($e);
}

echo $doc->saveHTML($doc->documentElement);

这篇关于PHP DOMDocument:按类删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆