In the document object model (DOM) implementation in PHP, The DOMDocument class has two functions for saving xml files; save() and saveXML(). saveXML() is used to output the contents to a string and save() to output to a URI.
Serialize an xml:
1 | $output = $domdoc->saveXML(); |
The above line would serialize the DOMDocument object into
<main><sub>contents</sub></main>
The saveXML() takes an optional node parameter, which should also be a domdocument object. The resulting xml will be just an output of that parameter element.
1 | $output = $domdoc->saveXML($sub); |
The output would be
<sub>contents</sub>
using save():
1 | $size = $domdoc->save('outputdata.xml); |
The above code saves the document to the file outputdata.xml and returns the number of bytes written to the variable $size.
The newline characters, tabs, and spaces are removed in case of saveXML(). we can use formatOutput to save the xml with formatting.
1 2 | $domdoc->formatOutput = TRUE; echo $domdoc->saveXML(); |
Tags: dom, xml parsing, xml whitespace