PHP SimpleXMLElement - asXML() Method
The PHP SimpleXMLElement::asXML() method formats the parent object's data in XML version 1.0.
Syntax
public SimpleXMLElement::asXML(filename)
Parameters
filename |
Optional. If provided, the function writes the data to the file rather than returning it. |
Return Value
If the filename is not specified, this function returns a string on success and false on error. If the filename is specified, it returns true if the file was written successfully and false otherwise.
Example: get XML
The example below shows the usage of SimpleXMLElement::asXML() method.
<?php $xmlstr = <<<XML <userlist> <user id="John123"> <name>John Smith</name> <city>New York</city> <phone>+1-8054098000</phone> </user> <user id="Marry2015"> <name>Marry G.</name> <city>London</city> <phone>+33-147996101</phone> </user> </userlist> XML; $xml = new SimpleXMLElement($xmlstr); echo $xml->asXML(); ?>
The output of the above code will be:
<?xml version="1.0"?> <userlist> <user id="John123"> <name>John Smith</name> <city>New York</city> <phone>+1-8054098000</phone> </user> <user id="Marry2015"> <name>Marry G.</name> <city>London</city> <phone>+33-147996101</phone> </user> </userlist>
Example: using on SimpleXMLElement::xpath() results
In the example below, this function is used on SimpleXMLElement::xpath() result.
<?php $xmlstr = <<<XML <userlist> <user id="John123"> <name>John Smith</name> <city>New York</city> <phone>+1-8054098000</phone> </user> <user id="Marry2015"> <name>Marry G.</name> <city>London</city> <phone>+33-147996101</phone> </user> </userlist> XML; $xml = new SimpleXMLElement($xmlstr); //search for <userlist><user><name> $result = $xml->xpath('/userlist/user/name'); foreach($result as $node){ echo $node->asXML(); } ?>
The output of the above code will be:
<name>John Smith</name><name>Marry G.</name>
❮ PHP SimpleXML Reference