How can you efficiently delete empty nodes in a DOMDocument using PHP without causing errors or unintended side effects?

When deleting empty nodes in a DOMDocument using PHP, it's important to handle potential errors and unintended side effects that may arise from the deletion process. One efficient way to do this is by first identifying and storing a list of empty nodes to be deleted, and then removing them from the DOMDocument in a safe and controlled manner. This can help prevent any issues such as invalid node references or unexpected changes to the document structure.

// Load your XML content into a DOMDocument
$doc = new DOMDocument();
$doc->loadXML($xmlContent);

// Find and store empty nodes to be deleted
$emptyNodes = [];
foreach ($doc->getElementsByTagName('*') as $node) {
    if ($node->nodeValue === '') {
        $emptyNodes[] = $node;
    }
}

// Delete empty nodes from the DOMDocument
foreach ($emptyNodes as $emptyNode) {
    if ($emptyNode->parentNode) {
        $emptyNode->parentNode->removeChild($emptyNode);
    }
}

// Save the modified XML content
$modifiedXml = $doc->saveXML();