PHP DOMDocument notes
By Dave Redfern (Writer)
Published: 25 Nov 16:48 in Web Development
PHP5 includes a full DOMDocument object for building DOM compliant object trees. A slight abuse of this is for pretty-printing existing XML blocks. This is useful if you have a complex self-generated XML string that you want to output in a formatted manner but do not necessarily want to try and figure out how to implement it via tabs and newlines in strings. This obviously applies to existing code.
Output settings must be specified before saving out or loading your XML string:
$oDom = new DOMDocument(); $oDom->formatOutput = true; $oDom->preserveWhiteSpace = true;
Then you can load your XML via one of a number of methods:
$oDom->loadXML('a string of XML data'); $oDom->load('file.xml');
Finally to get your output, do the usual saveXML():
echo $oDom->saveXML();
Now all this is straight forward; why this post? Well it turns out that while this works for strings; it does not work on strings that contain any newlines, tabs or other formatting. You must strip out all of these characters - otherwise the ouput is not formatted regardless of the options previously specified.
So if you are intending to use DOMDocument to format your output in a similar manner to the above, and your XML generation includes newlines and tab characters, be sure to strip them (or better yet - remove them from the generation code) before passing your XML string into DOMDocument.