asXML() can return the XML document as a string or write it directly to a file.
<?php
$xml = new SimpleXMLElement('<book><title>PHP</title></book>');
$xmlText = $xml->asXML();
echo $xmlText;
?>The examples below show additional XML structures, return values, and practical uses.
<?php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
echo $main1->asXML(); // string output
?>
To write the same string to a file we will change the above code like this.
echo $main1->asXML('data.xml'); // writing to file
The call writes the XML document to data.xml and returns true on success or false on failure. Use an application-controlled path and verify that the target directory is writable.
<?php
$xml = new SimpleXMLElement('<root></root>');
$xml->addChild('item', 'Apple');
echo $xml->asXML(); // Output: XML string
?>
<?php
$xml->asXML('data.xml'); // Writes XML to a file named data.xml
?>
<?php
$xml = new SimpleXMLElement('<fruits></fruits>');
$xml->addChild('fruit', 'Apple');
$xml->addChild('fruit', 'Banana');
$xml->addChild('fruit', 'Cherry');
echo $xml->asXML(); // Output: XML string with all fruits
?>
<?php
$xml = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book', 'PHP Programming');
$book->addAttribute('id', '101');
echo $xml->asXML(); // Output: XML string with attributes
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.