How to save changed SimpleXML object back to file?

How to save changed SimpleXML object back to file?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Save Changes Made to SimpleXML Objects

When working with XML in PHP, the SimpleXMLElement object provides a convenient way to parse and manipulate structures that resemble objects. However, a common pitfall arises when you modify these objects in memory without persisting those changes back to the disk. The code snippet provided demonstrates exactly this scenario: loading an XML file, removing a specific node (Passage), adding a new one with updated data, and then halting execution.

The immediate issue is that SimpleXML behaves like a live view of the file rather than a direct container for data. When you use functions like unset(), addChild(), or modify attributes on the loaded object, you are altering the in-memory representation. If you do not explicitly serialize this modified state back to a file, the changes exist only while the script is running. Once the script finishes, the original XML file remains untouched.

To persist the modifications, you must use the SimpleXMLElement::asXML() method. This static method accepts the modified object and returns a string containing the serialized XML. You then need to write this string back to the file system using standard PHP file handling functions like file_put_contents(). Without this explicit save step, your application logic effectively performs a no-op regarding the data storage layer.

Here is how you can refactor the provided function to ensure data integrity:

public function hint_insert() {
    foreach($this->hints as $key => $value) {
        $filename = $this->get_qid_filename($key);
        
        // Load the file
        $xml = simplexml_load_file($filename);
        
        if ($xml === false) {
            throw new Exception("Failed to load XML file: " . error_get_last()['message']);
        }

        foreach ($xml->PrintQuestion as $PrintQuestion) {
            // Modify the object in memory
            unset($xml->PrintQuestion->content->multichoice->feedback->hint->Passage);
            
            // Ensure the parent element exists before adding children to avoid null pointer issues
            if (!isset($xml->PrintQuestion->content->multichoice->feedback->hint)) {
                $xml->PrintQuestion->content->multichoice->feedback->addChild('hint');
            }

            $xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]);

            // CRITICAL: Serialize and save back to file
            $xmlString = $xml->asXML();
            
            if (!file_put_contents($filename, $xmlString)) {
                throw new Exception("Failed to save changes to: " . $filename);
            }

            break; // Exit loop after processing the first match or intended target
        }
    }
}

There is a subtle but significant difference between how SimpleXML handles memory and how it handles persistence. When you access nodes via properties (e.g., $xml->node), PHP creates an object reference to that node in memory. Modifying these nodes changes the internal state of the loaded object, not the file on disk. The asXML() method reconstructs the DOM tree from this modified object and outputs it as a string. Writing that string back to the file is the only way to make the modifications permanent.

One potential pitfall in the original code involves the use of unset(). While SimpleXML allows removing children nodes, doing so repeatedly or incorrectly can lead to fragmented objects or errors if the parent node structure becomes invalid. Furthermore, simply echoing print_r($PrintQuestion) inside the loop does not help with debugging because it only displays the current memory state, not the file content. If you need to verify what was actually saved, inspecting the output of $xml->asXML() is more reliable than printing intermediate object states.

If your XML structure is complex or if performance becomes a bottleneck with large files, consider using DOMDocument instead. The DOM API offers more control over saving options, such as formatting whitespace and handling namespaces explicitly. However, for straightforward modifications like the one shown here, sticking with SimpleXML and remembering to call asXML() followed by file_put_contents() is the most efficient approach.

For developers building larger projects where XML manipulation is a recurring theme, exploring dedicated libraries or frameworks can streamline these operations. Resources like https://laravelcompany.com often provide insights into best practices for handling file I/O within modern PHP ecosystems, ensuring that your data persistence logic remains robust and maintainable.

Our network