asXML string output, writing to file , xml string to file

We have seen how we can create a SimpleXMLElement object. Now we will translate the XML data to a string by using asXML function. Here is the sample code. We have already used our XML data sample file for this.

xml-sample1.php

<?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

Example 1: Creating and Displaying XML

<?php
$xml = new SimpleXMLElement('<root></root>');
$xml->addChild('item', 'Apple');
echo $xml->asXML();  // Output: XML string
?>

Example 2: Writing XML to a File

<?php
$xml->asXML('data.xml');  // Writes XML to a file named data.xml
?>

Example 3: Adding Multiple Elements to 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
?>

Example 4: Adding Attributes to XML Elements

<?php
$xml = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book', 'PHP Programming');
$book->addAttribute('id', '101');
echo $xml->asXML();  // Output: XML string with attributes
?>

XML XML Children

Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate 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.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer