PHP | SimpleXMLElement saveXML() Function

The SimpleXMLElement::saveXML() function is an inbuilt function in PHP which return well-formed XML string from a SimpleXML object. It is an alias of SimpleXMLElement::asXML() function.

Syntax:

mixed SimpleXMLElement::saveXML( string $filename )

Parameter: 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: This function 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.

Below programs illustrate the SimpleXMLElement::saveXML() function in PHP:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Loading XML document to $user
$user = <<<XML
<user>
    <username> user123 </username>
    <name> firstname lastname </name>
    <phone> +91-9876543210 </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->saveXML();
echo $xml->saveXML('savexmltofile.xml');
?>

chevron_right


Output:

user123 firstname lastname +91-9876543210 I am John Doe. Live in Kolkata, India. 1

Saved XML file:

Program 2: Save XML filename by using sample.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0"?>
<user>
    <username> user123 </username>
    <name> firstname lastname </name>
    <phone> +91-9876543210 </phone>
    <detail> I am John Doe. Live in Kolkata, India. </detail>
</user>

chevron_right


index.php

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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->saveXML();
echo $xml->saveXML('savexmltofile.xml');
?>

chevron_right


Output:

user123 firstname lastname +91-9876543210 I am John Doe. Live in Kolkata, India. 1

saved XML file:

Reference: https://www.php.net/manual/en/simplexmlelement.asxml.php



My Personal Notes arrow_drop_up

I am a programmer by hobby

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.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.