How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?

Linda Hamilton
Release: 2024-11-02 02:48:02
Original
924 people have browsed it

How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?

Deleting Elements from DOMDocument

It's often necessary to manipulate the content of HTML documents loaded with DOMDocument. One common task is to remove elements from the DOM.

Consider the following code:

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

foreach($dom->getElementsByTagName('a') as $href)
    if($href->nodeValue == 'First')
        //delete</code>
Copy after login

How can the First element be removed from the DOM without creating a new document?

Solution

To remove a node, instruct the parent node to remove the child:

<code class="php">$href->parentNode->removeChild($href);</code>
Copy after login

Refer to the $parentNodeDocs property of DOMNode and removeChild()Docs method for further details.

Related Questions

  • How to remove attributes using PHP DOMDocument?
  • How to remove an HTML element using the DOMDocument class

The above is the detailed content of How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?. 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!