Stripping a Tag and Its Nested Content Using Tag ID with PHP Native DOM
Stripping specific HTML elements along with their inner content can be a common task in web development. In this case, you seek to remove the contents within a specific
Solution:
PHP Native DOM provides a robust set of methods for manipulating HTML documents. To remove the specified nested content:
Code:
<code class="php">$dom = new DOMDocument; $dom->loadHTML($htmlString); $xPath = new DOMXPath($dom); $nodes = $xPath->query('//*[@id="anotherDiv"]'); if($nodes->item(0)) { $nodes->item(0)->parentNode->removeChild($nodes->item(0)); } echo $dom->saveHTML();</code>
This code will remove everything starting from the
The above is the detailed content of How to Remove a Specific HTML Element and Its Contents by ID Using PHP Native DOM?. For more information, please follow other related articles on the PHP Chinese website!