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

Barbara Streisand
Release: 2024-10-30 07:12:28
Original
594 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!