Home  >  Article  >  Backend Development  >  How to Remove Elements from a DOMDocument in PHP Without Creating a New One?

How to Remove Elements from a DOMDocument in PHP Without Creating a New One?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 07:12:28594browse

How to Remove Elements from a DOMDocument in PHP Without Creating a New One?

Removing Elements with DOMDocument

In PHP, you can easily load and manipulate HTML documents using the DOMDocument class. However, you may encounter a need to remove elements from the loaded DOM, and this document will guide you through this process without creating a new DOM.

To delete an element from the DOMDocument, the parent node's removeChild() method must be employed. Here's how to do it:

<code class="php"><?php
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('a') as $href) {
    if($href->nodeValue == 'First')
        $href->parentNode->removeChild($href);
}
?></code>

In this code, the removeChild() method is called on the parent node of the element to be deleted. The parentNode property of a DOMNode object references the parent node, and the removeChild() method removes the specified child node from the parent.

By utilizing the parentNode->removeChild() method, you can effectively remove elements from the DOM, allowing you to modify the structure of the loaded HTML document.

The above is the detailed content of How to Remove Elements from a DOMDocument in PHP Without Creating a New One?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn