W3docs

__tostring()

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

SimpleXMLElement::asXML()

SimpleXML is a PHP extension that provides an API for working with XML documents. The SimpleXMLElement::asXML() method converts a SimpleXMLElement object back into an XML string. This article covers its usage and parameters.

Understanding the SimpleXMLElement::asXML() function

The SimpleXMLElement::asXML() function generates an XML document from a SimpleXMLElement object. It returns the XML document as a string, or writes it to a file if a filename is provided. The syntax is as follows:

asXML ([ string $filename = null ] ) : string|false

Here, $filename is an optional parameter that specifies the filename to save the XML document. If $filename is not specified, the XML document is returned as a string. If provided, the function returns true on success, or false on failure (e.g., due to permission issues or invalid paths).

Note: The encoding of the output string is determined by the encoding attribute in the XML declaration. If not specified, it defaults to UTF-8.

Example Usage

Let's look at an example to understand the usage of the SimpleXMLElement::asXML() function in PHP:

<?php

$xml = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book');
$book->addChild('title', 'PHP Basics');
$book->addChild('author', 'John Doe');

echo $xml->asXML();

You can test this code interactively using the try-it button below:

In the example above, we create a SimpleXMLElement object representing an empty XML document. We add a book element using the addChild() method, followed by title and author child elements. Finally, we output the XML document as a string using asXML().

To demonstrate the optional $filename parameter, you can save the output directly to a file. It is recommended to check the return value to handle potential errors:

<?php

$xml = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book');
$book->addChild('title', 'PHP Basics');
$book->addChild('author', 'John Doe');

if ($xml->asXML('output.xml')) {
    echo "XML saved successfully.";
} else {
    echo "Failed to save XML.";
}

Conclusion

The SimpleXMLElement::asXML() function allows developers to serialize a SimpleXMLElement object back into an XML string or save it directly to a file. It is a straightforward way to handle XML generation and persistence in PHP.

Practice

Practice

What is the function of the __toString() method in PHP?