What is the best way to recursively search through a DOMDocument in PHP to find and remove specific nodes?
When recursively searching through a DOMDocument in PHP to find and remove specific nodes, you can use a recursive function that traverses the DOM tree and checks each node for the desired criteria. If a node matches the criteria, it can be removed using the `removeChild()` method. This approach ensures that all nested nodes are also searched and removed if necessary.
function removeNodesByTagName(DOMNode $node, string $tagName) {
$children = $node->childNodes;
for ($i = $children->length - 1; $i >= 0; $i--) {
$child = $children->item($i);
if ($child->nodeType === XML_ELEMENT_NODE && $child->tagName === $tagName) {
$node->removeChild($child);
} else {
removeNodesByTagName($child, $tagName);
}
}
}
// Example usage
$doc = new DOMDocument();
$doc->loadHTML($html);
removeNodesByTagName($doc, 'div');
echo $doc->saveHTML();
Keywords
Related Questions
- What resources or documentation are available for PHP developers looking to improve their understanding of MySQL database interactions?
- How can PHP be used to dynamically generate and display images based on data retrieved from a database, such as changing colors or positions based on database values?
- How can you escape quotation marks when including images in PHP code?