<?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('test.php'); // writing to file
Above line will create the file test.php and on successful will return 1
<?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.