W3Mentor’s guide to simpleXML : Part 2 – Saving XML Data

The asXML() method in SimpleXML is used to save/output XML data. asXML allows us to output a document or subtree to a string or a file. It is important to call the asXML() method from the correct node to output it. The output depends upon the node from which this method is called. When called from the document element, the entire document is output. When called from any other node within the tree, the entire node and any subtree are output.

Example code:

1
2
3
$xml = "<root><child>childcontent</child></root>";
$se = new SimpleXMLElement($xml);
print $se->asXML();

Generated output:

1
2
<?xml version="1.0"?>
<root><child>childcontent</child></root>

In the example above, we called the asXML() method from the document element. The document element is the element returned from the initial load functions.

We can also pass a filename to the asXML method, which causes SimpleXML to save the XML to the named file.

Example code:

1
2
3
$xml = "<root><child>childcontent</child></root>";
$se = new SimpleXMLElement($xml);
$se->asXML('somefilename.xml');
Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone