asXML string output, writing to file , xml string to file
PHP XML
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.
<?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
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com