XML PHP Pretty Printer


<?
/** Prettifies an XML string into a human-readable and indented work of art
 *  @param string $xml The XML as a string
 *  @param boolean $html_output True if the output should be escaped (for use in HTML)
 */
function xmlpp($xml, $html_output=false) {
    $xml_obj = new SimpleXMLElement($xml);
    $level = 4;
    $indent = 0; // current indentation level
    $pretty = array();
    
    // get an array containing each XML element
    $xml = explode("\n", preg_replace('/>\s*</', ">\n<", $xml_obj->asXML()));

    // shift off opening XML tag if present
    if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
      $pretty[] = array_shift($xml);
    }

    foreach ($xml as $el) {
      if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
          // opening tag, increase indent
          $pretty[] = str_repeat(' ', $indent) . $el;
          $indent += $level;
      } else {
        if (preg_match('/^<\/.+>$/', $el)) {            
          $indent -= $level;  // closing tag, decrease indent
        }
        if ($indent < 0) {
          $indent += $level;
        }
        $pretty[] = str_repeat(' ', $indent) . $el;
      }
    }   
    $xml = implode("\n", $pretty);   
    return ($html_output) ? htmlentities($xml) : $xml;
}

echo '<pre>' . xmlpp($xml, true) . '</pre>';
?>

15 comments:

Chris Buenafe said...

nice code you have.

axah said...

Hey Eric,

great work. Runs out of the box :-)

Thanks

Tim Chambers said...

Excellent code - worked fine for me.

You saved me lots of time - a valuable commodity.

Regards,

Tim

Eric (Google) said...

Thanks! Glad this helped.

Eric

vaibhav said...

Hey Eric, short and sweet code.
Thanks :)

zeropadded said...

Excellent, thanks a lot!

Kawika said...

This function helped me out a lot. Thanks!

thInk said...

can anyone please tell me how do i use this function?

D-FENSE said...

brilliant... nice and easy!

Tomás García said...

Thx for the code!
Funciona perfectamente!

Patty Hayes said...

Would you be willing to put a license on this code? public-domain? GPL? bsd? I'd like to use it, but legally can't until you do!

Eric (Google) said...

At the bottom:

All code licensed under the Apache 2.0 License.

Frank de Weger said...

I might be missing something really obvious, but i think if you leave out the declaration of the SimpleXMLEelement and use

$xml = explode("\n", preg_replace('/>\s*\n<", $xml));

instead, you get the same reults...

kosovohp said...

socks5 | socks proxy | proxy free | proxy
socks proxy | socks5 | proxy | proxy free

kosovohp said...

Girl Xinh | Hot Girl | Cute Girl | Sexy Girl | Hot Girl Asian
Hot Girl | Lexi Belle | Sexy Girl | Cute Girl | Hot Asian Girl | Leah Dizon | Hot Girl Asian | Girl Xinh
socks proxy | socks5 | proxy free |proxy list