PHP | SimpleXMLElement asXML() Function
Pre-requisite: Read XML
The SimpleXMLElement::asXML() function is an inbuilt function in PHP which returns well-formed XML string from a SimpleXML object.
Syntax:
mixed SimpleXMLElement::asXML( $filename )
Parameters: This function accepts single parameter $filename which is optional. It specified this function save data to the file instead of returning as XML.
Return Value: It returns a String representing the data and filename if it is specified on success or returns False on failure.
Note: This function is available for PHP 5.0.1 and newer version.
Example 1:
<?php // Loading XML document to $user $user = <<<XML <user> <username> user123 </username> <name> firstname lastname </name> <phone> +91-XXXXXXXXXX </phone> <detail> I am John Doe. Live in Kolkata, India. </detail> </user> XML; // Creating new SimpleXMLElement object from $user $xml = new SimpleXMLElement($user); // Printing as XML echo $xml->asXML(); echo $xml->asXML('savexmltofile.xml'); ?> |
Output:
user123 firstname lastname +91-XXXXXXXXXX I am John Doe. Live in Kolkata, India. 1
Saved XML file:

Example 2: Save XML filename by using sample.xml
<?xml version="1.0"?> <user> <username> user123 </username> <name> firstname lastname </name> <phone> +91-XXXXXXXXXX </phone> <detail> I am John Doe. Live in Kolkata, India. </detail> </user> |
index.php
<?php // Loading XML document from sample.xml to // $user and creating new SimpleXMLElement // object $xml = new SimpleXMLElement("sample.xml", 0, TRUE); // Printing data as xml document echo $xml->asXML(); echo $xml->asXML('savexmltofile.xml'); ?> |
Output:
user123 firstname lastname +91-9876543210 I am John Doe. Live in Kolkata, India. 1
Saved XML file:

Recommended Posts:
- PHP | SimpleXMLElement getDocNamespaces() Function
- PHP | SimpleXMLElement XPath() Function
- PHP | SimpleXMLElement attributes() Function
- PHP | SimpleXMLElement getNamespaces() Function
- PHP | SimpleXMLElement saveXML() Function
- PHP | SimpleXMLElement registerXPathNamespace() Function
- PHP | SimpleXMLElement count() Function
- PHP | SimpleXMLElement addAttribute() Function
- PHP | SimpleXMLElement::__construct() Function
- PHP | SimpleXMLElement children() Function
- PHP | SimpleXMLElement addChild() Function
- PHP | SimpleXMLElement::getName() Function
- How to call a function that return another function in JavaScript ?
- How to get the function name inside a function in PHP ?
- How to get the function name from within that function using JavaScript ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

