Using SimpleXML to create an XML object from scratch

Using SimpleXML to create an XML object from scratch

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

Stefan Bogdanescu

Founder & Senior Architect

Using SimpleXML to create an XML object from scratch

Developers often encounter a specific constraint when working with PHP's DOM and SimpleXML: they want to generate an XML structure programmatically without relying on simplexml_load_string(). This function is designed for parsing existing strings, meaning it requires you to hardcode a root element before you can manipulate children. While effective, this approach feels like a workaround if your goal is to build the document tree from nothing but code. The DOM extension offers a cleaner API for this specific use case, allowing you to instantiate a DOMDocument and populate it via DOMElement objects before serializing it back into an XML string or stream.

The core distinction lies in how these libraries handle memory and object initialization. When you call simplexml_load_string('root'), SimpleXML implicitly creates the root node based on that hardcoded string. In contrast, DOM allows you to explicitly create the document instance first using new DOMDocument(). Once instantiated, you can retrieve or create a root element using methods like createElement() or appendChild(). This separation of concerns—initializing the container before adding content—is generally preferred for programmatic generation because it avoids the need to maintain a template string in your code.

Consider a scenario where you are building an RSS feed or a specific API response format. You might start by creating the document and setting the encoding, which is a common requirement for valid XML:

$dom = new DOMDocument();
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// Create the root element programmatically
$root = $dom->createElement('feed');
$root.setAttribute('xmlns', 'http://example.com/ns');
$dom->appendChild($root);

// Add children without any hardcoded strings
$title = $dom->createElement('title');
$title->textContent = 'My Dynamic Feed';
$root->appendChild($title);

$dom->saveXML();

This approach ensures that your XML structure is defined entirely by your application logic. You can add namespaces, attributes, and nested elements dynamically without worrying about the order of operations relative to a static string. The DOM API provides a robust set of methods for appending children, setting text content, and managing attributes, making it the standard tool for constructing XML from scratch.

However, there are trade-offs to consider regarding performance and complexity. The DOM extension is more memory-intensive than SimpleXML because it maintains a full tree structure in memory. For small documents or rapid prototyping, this overhead might be negligible. But if you are processing massive datasets or building high-throughput applications, the memory footprint of a fully parsed DOM tree could become a bottleneck. In such cases, streaming parsers like XMLWriter or even carefully constructed SimpleXML strings might offer better efficiency, though they introduce their own complexity regarding attribute handling and namespace management.

Another pitfall to watch for involves the DOMDocument constructor. If you do not explicitly set the version (e.g., "1.0") or encoding before appending elements, some parsers downstream might infer defaults that differ from your expectations. Additionally, while DOM is powerful, it requires more verbose code than SimpleXML's concise string manipulation. If you only need to modify an existing XML file and don't require a fresh start, sticking with simplexml_load_string() remains a valid option despite the initial "hack" feeling of providing a root string.

Ultimately, the choice depends on whether you are parsing or creating. For creation tasks, DOM offers the necessary abstraction to build complex trees without template strings. The slight increase in code verbosity is often worth the clarity of separating document initialization from content population.

Our network