Today I had to find a simple way to format a parsed xml-string into a pretty looking output for a file and the screen. My search on Google return this stackoverflow-comment which helped me out.
I thought I’d share it with the world.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /** * formats the xml output readable * * @param $simpleXmlObject instance of SimpleXmlObject to pretty-print * @return string of indented xml-elements */ function format(&$simpleXmlObject){ if( ! is_object($simpleXmlObject) ){ return ""; } //Format XML to save indented tree rather than one line $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($simpleXmlObject->asXML()); return $dom->saveXML(); } |
PS: In case you don’t know how to get a SimpleXml-Object.
If this article helped you, please consider to flattr it. Thanks.