Format output of $SimpleXML->asXML();

Format output of $SimpleXML->asXML();

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

Stefan Bogdanescu

Founder & Senior Architect

Formatting SimpleXML Output for Human Readability

When working with PHP's SimpleXML extension, you often find yourself manipulating XML structures dynamically. As shown in standard examples, creating a document node by node is straightforward:

$xmlstr = <<<'XML'
<?xml version='1.0' standalone='yes'?><movies></movies>
XML;

$sxe = new SimpleXMLElement($xmlstr);

$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo("<pre>".htmlspecialchars($sxe->asXML())."</pre>");

The output from $sxe->asXML() is technically valid and perfectly suitable for programmatic consumption. However, when debugging or inspecting the structure manually, that single-line string is difficult to parse visually. The core issue isn't the content; it's the lack of whitespace indentation.

PHP's SimpleXMLElement object does not provide a built-in method to format the output with newlines and indentation directly. The asXML() method returns the raw XML string exactly as it was constructed in memory, without applying pretty-printing logic. To achieve a readable, indented format for human inspection, you need to externalize the formatting process.

Using DOMDocument for Pretty-Printing

The standard approach in PHP is to convert the SimpleXMLElement object into a DOMDocument instance. The DOMDocument class offers a built-in formatOutput() method and an saveXML() method that support pretty-printing, unlike the SimpleXMLElement API.

Here is how you can migrate the data:

// Create the DOMDocument
$dom = new DOMDocument();

// Convert SimpleXML to DOM
$sxe->registerXPathNamespace('s', 'http://www.w3.org/2001/XMLSchema'); // Optional namespace handling
$dom->loadXML((string)$sxe);

// Enable pretty printing
$dom->formatOutput = true;

// Save the formatted XML to a string
$formattedXml = $dom->saveXML();

echo("<pre>".htmlspecialchars($formattedXml)."</pre>");

Once $dom->formatOutput is set to true, calling saveXML() will return the same data with proper indentation and line breaks. This makes the output significantly more readable for debugging purposes while maintaining strict XML validity.

Handling Namespace URIs

One potential pitfall when using DOMDocument to reformat SimpleXMLElement data is namespace handling. If your original XML contains namespaces, simply converting via loadXML() might alter namespace declarations or attribute prefixes depending on how the DOM parser interprets the default namespace context.

In many simple cases, like the example above with no explicit namespaces defined in the source string, the conversion works seamlessly. However, if you are dealing with complex schemas where namespace URIs are critical to the document structure, ensure that the DOMDocument preserves them correctly. You may need to manually inspect the resulting XML to confirm that attributes and elements retain their intended namespaces after the format operation.

When to Use Formatted vs. Raw Output

There is a clear trade-off involved here. The raw output from asXML() is compact and efficient for sending over networks or storing in databases where whitespace is irrelevant to the data integrity. Programmatic consumers typically ignore trailing newlines and indentation, treating the XML as a stream of tokens.

However, for logging, unit testing assertions, or any scenario where a developer needs to visually verify the structure of the generated document, formatted output is essential. Relying solely on asXML() for debugging can lead to confusion when comparing expected structures against actual outputs in large files.

If you are building a library or an API endpoint using Laravel, consider this formatting step only during development or within dedicated logging middleware. In production responses, keep the XML compact unless your client specifically requests pretty-printed payloads. For more robust XML generation workflows in larger applications, exploring packages that handle DOM manipulation with namespace safety might be warranted, especially if you find yourself repeatedly converting between SimpleXML and DOMDocument.

Our network