Create new XML file and write data to it?

Create new XML file and write data to it?

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

Stefan Bogdanescu

Founder & Senior Architect

Managing XML Lifecycle in PHP: From Creation to Iterative Updates

Building a new XML file and populating it with base nodes is a common requirement when handling structured data, yet the implementation details often trip up developers who are comfortable with simple string manipulation or basic database operations. The core challenge lies not just in generating the markup, but in managing the file lifecycle: creating the initial document structure, persisting it, and then reopening that specific stream to append subsequent data without corrupting existing content.

When you start fresh, the approach differs significantly from appending to an existing log or configuration file. You are dealing with a document model where order and hierarchy matter immensely. If your goal is to write base nodes first, save the file, and later reopen it to add more data, you must ensure that the initial file_put_contents() call establishes a valid XML root element. A malformed root node will cause parsers to fail immediately upon the next read operation.

For the initial creation phase, constructing the XML string in memory before writing to disk is often the cleanest strategy. This allows you to build your document object model (DOM) or simple string templates without worrying about file locking or partial writes interfering with each other. Once the base structure—typically a single <root> element containing your initial child nodes—is ready, use file_put_contents() with standard write permissions to persist it. Ensure the target directory exists and is writable; failing here results in a silent failure or an exception that can be hard to debug if not explicitly checked.

<?php
// Initial creation: Build structure in memory then write
$xmlContent = '<?xml version="1.0" encoding="UTF-8"?>
<root>
    <item id="1">Base Node One</item>
    <item id="2">Base Node Two</item>
</root>';

// Write to disk
file_put_contents('data/basics.xml', $xmlContent);

The critical moment arrives when you need to return and write more data. You cannot simply append a string of XML nodes to the file unless you are strictly appending to a list inside an existing parent element, which is often not how XML schemas are designed. If your new data belongs as a child of <root>, you must open the file in read-write mode.

Using fopen() with 'r+' mode allows you to seek to the end of the file and append data safely. However, there is a significant pitfall here: XML parsers generally require a single root element. If your current file has one <root> and you simply write new nodes to the end without wrapping them in a new parent or modifying the existing structure, you risk creating multiple root elements if not handled carefully, or leaving the file in an invalid state between reads.

The robust approach for iterative updates is to read the entire content, parse it into a DOM object, modify the document tree programmatically, and then serialize it back out. This guarantees that the XML remains well-formed regardless of how many times you update it.

<?php
// Open existing file in read-write mode
$fp = fopen('data/basics.xml', 'r+');

// Seek to end of file
fseek($fp, 0, SEEK_END);

// Append new data as a string (simplest for flat lists)
$newData = '<item id="3">New Node Three</item>';
fwrite($fp, $newData);
fclose($fp);

// For complex structures where root integrity matters, 
// parsing and re-serializing is safer to avoid syntax errors.

If your schema requires strict adherence to a specific hierarchy or you need to modify existing attributes, relying on string concatenation becomes error-prone quickly. In those scenarios, leveraging SimpleXMLElement or the DOMDocument class is essential. These classes allow you to load the existing XML into memory, create new child elements, set their properties, and save the updated document back to the same path.

This method eliminates the risk of creating duplicate root nodes or breaking namespaces. It treats the file as a mutable state rather than a static text blob. While slightly more verbose, it provides the safety required for production systems where data integrity is non-negotiable. If you are working within a Laravel application, consider using a service class to encapsulate this logic, ensuring that your XML handling remains decoupled from your controllers and easier to test in isolation.

Our network