format xml string format xml string xml xml

format xml string


With DOM you can do

$dom = new DOMDocument;$dom->preserveWhiteSpace = FALSE;$dom->loadXML('<root><foo><bar>baz</bar></foo></root>');$dom->formatOutput = TRUE;echo $dom->saveXML();

gives (live demo)

<?xml version="1.0"?><root>  <foo>    <bar>baz</bar>  </foo></root>

See DOMDocument::formatOutput and DOMDocument::preserveWhiteSpace properties description.


This function works perfectlly as you want you don't have to use any xml dom library or nething just pass the xml generated string into it and it will parse and generate the new one with tabs and line breaks.

function formatXmlString($xml){    $xml = preg_replace('/(>)(<)(\/*)/', "$1\n$2$3", $xml);    $token      = strtok($xml, "\n");    $result     = '';    $pad        = 0;     $matches    = array();    while ($token !== false) :         if (preg_match('/.+<\/\w[^>]*>$/', $token, $matches)) :           $indent=0;        elseif (preg_match('/^<\/\w/', $token, $matches)) :          $pad--;          $indent = 0;        elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $token, $matches)) :          $indent=1;        else :          $indent = 0;         endif;        $line    = str_pad($token, strlen($token)+$pad, ' ', STR_PAD_LEFT);        $result .= $line . "\n";        $token   = strtok("\n");        $pad    += $indent;    endwhile;     return $result;}


//Here is example using XMLWriter

$w = new XMLWriter;$w->openMemory();$w->setIndent(true);  $w->startElement('foo');    $w->startElement('bar');      $w->writeElement("key", "value");    $w->endElement();  $w->endElement();echo $w->outputMemory();

//out put

<foo>  <bar>   <key>value</key>  </bar> </foo>