<?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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.