What best practices should be followed when handling XML files in PHP to avoid data corruption?

When handling XML files in PHP, it is important to properly sanitize and validate the data to avoid data corruption. One common issue is injection attacks where malicious XML content can be injected into the file, potentially causing data corruption. To prevent this, always use proper XML parsing functions and sanitize user input before inserting it into the XML file.

// Example of properly handling XML files in PHP to avoid data corruption

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

// Sanitize user input before inserting into the XML file
$newData = htmlspecialchars($_POST['data']);

// Add the new data to the XML file
$newNode = $xml->addChild('node', $newData);

// Save the changes back to the XML file
$xml->asXML('data.xml');