How can one effectively navigate and manipulate the tree structure of an XML document in PHP to retain specific elements while removing others?

To effectively navigate and manipulate the tree structure of an XML document in PHP to retain specific elements while removing others, you can use the SimpleXMLElement class to parse the XML document, loop through the elements, and use conditional statements to determine which elements to keep or remove.

$xml = <<<XML
<root>
    <element1>Keep this</element1>
    <element2>Remove this</element2>
</root>
XML;

$doc = new SimpleXMLElement($xml);

foreach ($doc->children() as $child) {
    if ($child->getName() == 'element1') {
        echo $child->asXML(); // Output or save the element
    }
}