Function
SimpleXMLElement::asXML()- is a built-in PHP function that returns a well-formed XML string from a SimpleXML object.
Syntax:mixed SimpleXMLElement::asXML ($filename)
Parameters:This function takes one parameter,
$filename, which is optional. It specifies a function to save data to a file instead of returning it as XML.
Returned value:Returns a string representing the data and file name if specified on success, or false in error.
Note.This feature is available for PHP 5.0.1 and later.
Example 1:
// Load XML document into $user
$user
= < < < XML
< user >
< username > user123 < / username >
< name > firstname lastname < / name >
+ 91-XXXXXXXXXX < / phone >
< detail >
I am John Doe. Live in Kolkata, India.
< / detail >
< / user >
XML;
// Create a new SimpleXMLElement object from $user
$xml
=
new
SimpleXMLElement (
$user
);
// Print in XML format
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.Storing the XML filename with 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
// Load the XML document from sample.xml into
// $user and create a new SimpleXMLElement
// object
$xml
=
new
SimpleXMLElement (
"sample.xml"
, 0, TRUE);
// Print data as XML
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: