What are some common pitfalls to avoid when working with XML files in PHP, especially when renaming nodes?

One common pitfall when working with XML files in PHP, especially when renaming nodes, is not properly handling namespaces. When renaming nodes, it's important to consider any namespaces that may be present in the XML document and ensure they are accounted for in the new node names.

// Load the XML file
$xml = simplexml_load_file('example.xml');

// Define the namespace
$ns = $xml->getNamespaces(true)['ns'];

// Find and rename nodes with namespaces
foreach ($xml->children($ns) as $node) {
    $node->addChild('newNode', (string)$node);
    unset($node[0]);
}

// Save the modified XML
$xml->asXML('modified.xml');