Home >Backend Development >PHP Tutorial >How to Remove HTML Elements by ID Using DOMXPath in PHP?
Stripping HTML Elements by ID with DOMXPath
Removing a portion of HTML, including a specific element and its inner contents, can be achieved using the DOMXPath interface in PHP. Let's consider a scenario where you have the following HTML:
<code class="html"><html> <body> bla bla bla bla <div id="myDiv"> more text <div id="anotherDiv"> And even more text </div> </div> bla bla bla </body> </html></code>
Your goal is to eliminate everything from
<?php // Load the HTML document $dom = new DOMDocument; $dom->loadHTML($htmlString); // Create a DOMXPath instance $xPath = new DOMXPath($dom); // Query for the target element $nodes = $xPath->query('//*[@id="anotherDiv"]'); // If the element exists if ($nodes->item(0)) { // Remove the element and its children $nodes->item(0)->parentNode->removeChild($nodes->item(0)); } // Output the modified HTML echo $dom->saveHTML();
This code will effectively remove the
The above is the detailed content of How to Remove HTML Elements by ID Using DOMXPath in PHP?. For more information, please follow other related articles on the PHP Chinese website!