W3docs

registerXPathNamespace()

SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The SimpleXMLElement::saveXML() function is one of the

SimpleXMLElement::saveXML()

SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The SimpleXMLElement::saveXML() method is one of the core functions provided by SimpleXML. It allows you to export an XML document represented by a SimpleXMLElement object as a string.

Understanding the SimpleXMLElement::saveXML() method

The SimpleXMLElement::saveXML() method exports an XML document. The syntax for modern PHP is as follows:

saveXML ( ?SimpleXMLElement $node = null, int $options = 0 ) : string|false

Here, $node is an optional parameter specifying a child node to export. If omitted, the entire document is exported. $options accepts bitwise flags from the LIBXML_* constants (e.g., LIBXML_NOEMPTYTAG) to control formatting and output behavior. The method returns the XML string on success, or false on failure. (Note: The nullable parameter syntax ?SimpleXMLElement requires PHP 7.1 or later.)

Example Usage

The following example demonstrates string output and saving to a file, along with basic error handling:

<?php

$xml = new SimpleXMLElement('<book><title>PHP Basics</title></book>');

// Return as a string
$xmlString = $xml->saveXML();
if ($xmlString !== false) {
    echo $xmlString;
}

// Save to a file
$xmlString = $xml->saveXML();
if ($xmlString !== false) {
    file_put_contents('output.xml', $xmlString);
    echo "XML saved successfully.";
} else {
    echo "Failed to save XML.";
}
?>

In the example above, we first create a SimpleXMLElement object representing an XML document with a book element containing a title child. We then call saveXML() without arguments to retrieve the XML as a string. Next, we pass that string to file_put_contents() to save the document directly to disk. The if checks ensure we handle potential false returns gracefully. (Note: Saving to a file requires write permissions for the target directory.)

Conclusion

The SimpleXMLElement::saveXML() method is an essential tool for working with XML in PHP. It provides a straightforward way to export XML data as a string using object-oriented syntax. By understanding its parameters and return values, developers can reliably manage XML documents in their applications.

Practice

Practice
What is the function of the registerXPathNamespace method in PHP?
What is the function of the registerXPathNamespace method in PHP?
Was this page helpful?