How to pretty-print a SimpleXmlObject in php

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.

About stevie

Born in the north of Germany, raised in Berlin and stayed there since. After graduating, studying applied computer science at the FHTW Berlin (now HTW Berlin), I started my own company with a former fellow student, providing high class application solutions for web and desktop for small and medium companies (see www.jnamic.com (english version to be finished) for more information). My personal favorite programming languages are PHP for the web and Java for everything else - although I must admit Java evolved very much in the past few years. I love to code and build new applications from the scratch, optimizing it through day and night till I am satisfied with it's performance. So follow my articles, share your thoughts and experience with me and have a good time browsing this blog!
This entry was posted in common and tagged , , , . Bookmark the permalink.

Leave a Reply