asXML()
Learn how PHP's SimpleXMLElement::asXML() returns XML as a string or writes it to a file, with examples and common gotchas.
Introduction
SimpleXMLElement::asXML() is the method you call when you are done building or modifying XML with SimpleXML and want the result back out - either as a string you can echo, return, or store, or written directly to a file. It is essentially the inverse of simplexml_load_string(): where loading turns XML text into an object you can navigate, asXML() turns that object back into XML text.
This page covers the two modes it works in, what it returns, how it behaves on a single node versus the whole document, and the gotchas that trip people up (no pretty-printing, no XML declaration on sub-nodes).
Syntax
// Mode 1: return the XML as a string
public SimpleXMLElement::asXML(): string|false
// Mode 2: write the XML to a file, return true/false
public SimpleXMLElement::asXML(string $filename): bool$filename(optional) - if given, the XML is written to this path and the method returnstrueon success orfalseon failure. If omitted, the XML is returned as a string instead.
asXML()andsaveXML()are aliases - they do exactly the same thing.
Returning XML as a string
Call asXML() with no argument to get the document as a string. This is the most common use - serialize, then echo, log, or send it as an HTTP response body.
Output:
<?xml version="1.0"?>
<books><book><title>PHP Basics</title><author>John Doe</author></book></books>We build the tree with addChild(), then asXML() serializes the whole thing. Notice the output is on a single line - SimpleXML does not indent or pretty-print. See Gotchas below for how to format it.
Calling asXML() on a single node
asXML() works on any element, not just the document root. Called on a child node it serializes only that node and its descendants - and, importantly, it omits the <?xml ... ?> declaration, because a fragment is not a standalone document.
<?php
$xml = new SimpleXMLElement(
'<books><book><title>PHP Basics</title></book></books>'
);
// Whole document - includes the XML declaration
echo $xml->asXML(), "\n";
// A single node - no declaration, just the fragment
echo $xml->book->title->asXML(), "\n";Output:
<?xml version="1.0"?>
<books><book><title>PHP Basics</title></book></books>
<title>PHP Basics</title>This makes asXML() handy for extracting one branch of a larger document as its own snippet.
Writing XML to a file
Pass a filename and asXML() writes the document there instead of returning a string. The return value is a boolean you should check, since the write can fail (bad path, no permission, full disk).
<?php
$xml = new SimpleXMLElement('<config><host>localhost</host></config>');
if ($xml->asXML('config.xml')) {
echo "Saved successfully\n";
} else {
echo "Failed to write file\n";
}When given a filename, asXML() returns true (not the XML string), so don't try to echo its result expecting the markup.
Gotchas
-
No pretty-printing.
asXML()emits compact, single-line XML. To indent it, hand the string to DOM:<?php $xml = new SimpleXMLElement('<a><b>hi</b></a>'); $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($xml->asXML()); echo $dom->saveXML();Output:
<?xml version="1.0"?> <a> <b>hi</b> </a> -
Sub-node output has no XML declaration - only the document root produces the
<?xml ... ?>line. -
falsemeans failure. When writing to a file, always test the boolean return rather than assuming success.
Related
addChild()- build the tree you serialize withasXML().saveXML()- the alias ofasXML().children()andattributes()- navigate the object before serializing.- Introduction to SimpleXML - the bigger picture of the SimpleXML extension.
Conclusion
SimpleXMLElement::asXML() serializes a SimpleXML object back into XML text. With no argument it returns the markup as a string; with a filename it writes the document to disk and returns a boolean. Remember that it produces compact output (use DOM if you need indentation) and that calling it on a child node yields a declaration-free fragment.