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

Convert an XML object to a string

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

Current example first; the detailed examples below are retained for additional learning and comparison.

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



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-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer