W3docs

saveXML()

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

Introduction

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 core methods provided by this extension. It allows you to serialize a SimpleXMLElement object back into an XML string or save it directly to a file. This article covers how to use the function effectively in PHP.

Understanding the SimpleXMLElement::saveXML() function

The SimpleXMLElement::saveXML() function serializes an XML document represented by a SimpleXMLElement object. The syntax is as follows:

saveXML ( [ ?string $filename [, int $options = 0 ]] ) : string|false
  • $filename: Optional. If provided, the XML is written to this file. If omitted, the function returns the XML as a string. Ensure the target directory exists and the process has write permissions to the file.
  • $options: Optional. Accepts LIBXML_* constants to modify the output, such as LIBXML_NOBLANKS or LIBXML_NOXMLDECL.
  • Return value: Returns a string containing the XML data when $filename is omitted. Returns false on failure when saving to a file.

Example Usage

Saving to a string

<?php

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

In the example above, we 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, which is printed to the output.

Saving to a file

<?php

$xml = new SimpleXMLElement('<book><title>PHP Basics</title></book>');
$success = $xml->saveXML('output.xml');

if ($success) {
    echo "XML saved successfully.";
} else {
    echo "Failed to save XML.";
}

When a $filename is provided, saveXML() writes the serialized XML directly to the specified file and returns a boolean indicating success or failure.

Conclusion

The SimpleXMLElement::saveXML() function is an essential tool for working with XML in PHP. It provides a straightforward way to serialize SimpleXMLElement objects into strings or persist them to files using object-oriented syntax. This guide has covered the function's parameters, return behavior, and practical usage. For more advanced XML manipulation, consider combining saveXML() with other SimpleXML methods or the DOMDocument extension.

Practice

Practice

In PHP, what steps can be used to generate an XML file from a PHP object?