In PHP, SimpleXMLElement::saveXML() turns a SimpleXML object back into an XML string, or writes that XML to a file when you pass a file name.
It is an alias of SimpleXMLElement::asXML(), so both methods do exactly the same thing. When you call it on the root element, the result starts with the XML declaration. When you call it on a child element, you get only that element. In modern code, prefer asXML() because it is the main name in the documentation.
Syntax
Call SimpleXMLElement::saveXML() with the values you need. Start with this line.
PHP
$xml->saveXML();
Call
What it does
$xml->saveXML()
Returns the whole document as an XML string, including the XML declaration.
$xml->title->saveXML()
Returns only the title element as a string, without a declaration.
$xml->saveXML('book.xml')
Writes the XML to book.xml and returns true when the file was saved.
saveXML() is an alias of asXML(). The two names give the same result, so pick asXML() in new code and use saveXML() only when you read older code. Any change you made through SimpleXML, such as a new value or a new child, is included in the output.
Optional. A file name or path. When you give it, PHP writes the XML to that file instead of returning it. When you leave it out or pass null, the XML is returned as a string.
Return Value
Return Value
Description
string
The XML text when no file name is given. It returns false if the XML could not be produced.
bool
true when a file name is given and the file is written, or false if writing fails.
PHP Examples
Example 1 — Get the XML as a String
Load a tiny XML string and turn it back into text with saveXML().
The file path is built inside the system temp folder, so it works on any computer.
saveXML($file) writes the XML to that file and returns true instead of returning a string.
file_get_contents() reads the file back, and trim() removes the final newline before printing.
unlink() deletes the temporary file, and file_exists() confirms that it is gone.
Frequently Asked Questions
It converts a SimpleXMLElement back into XML text. If you pass a file name, it writes the XML to that file and returns true instead.
Yes. saveXML() is an alias of asXML(), so both methods accept the same argument and return the same result. Use asXML() in new code.
When you call saveXML() on the root element, PHP adds the declaration at the top. If you call it on a child element, the declaration is not added.
Not directly. saveXML() writes the XML on one line. To get indented output, import the object into DOMDocument with dom_import_simplexml(), set formatOutput to true, and call saveXML() on the DOM object.
It returns true when the file is written, and false when it fails, for example because the folder does not exist or is not writable.