Indentation with DOMDocument in PHP
DomDocument will do the trick, I personally spent couple of hours Googling and trying to figure this out and I noted that if you use
$xmlDoc = new DOMDocument ();$xmlDoc->loadXML ( $xml );$xmlDoc->preserveWhiteSpace = false;$xmlDoc->formatOutput = true;$xmlDoc->save($xml_file);
In that order, It just doesn't work but, if you use the same code but in this order:
$xmlDoc = new DOMDocument ();$xmlDoc->preserveWhiteSpace = false;$xmlDoc->formatOutput = true;$xmlDoc->loadXML ( $xml );$xmlDoc->save($archivoxml);
Works like a charm, hope this helps
After some help from John and playing around with this on my own, it seems that even DOMDocument's inherent support for formatting didn't meet my needs. So, I decided to write my own indentation function.
This is a pretty crude function that I just threw together quickly, so if anyone has any optimization tips or anything to say about it in general, I'd be glad to hear it!
function indent($text){ // Create new lines where necessary $find = array('>', '</', "\n\n"); $replace = array(">\n", "\n</", "\n"); $text = str_replace($find, $replace, $text); $text = trim($text); // for the \n that was added after the final tag $text_array = explode("\n", $text); $open_tags = 0; foreach ($text_array AS $key => $line) { if (($key == 0) || ($key == 1)) // The first line shouldn't affect the indentation $tabs = ''; else { for ($i = 1; $i <= $open_tags; $i++) $tabs .= "\t"; } if ($key != 0) { if ((strpos($line, '</') === false) && (strpos($line, '>') !== false)) $open_tags++; else if ($open_tags > 0) $open_tags--; } $new_array[] = $tabs . $line; unset($tabs); } $indented_text = implode("\n", $new_array); return $indented_text;}
I have tried running the code below setting formatOutput
and preserveWhiteSpace
in different ways, and the only member that has any effect on the output is formatOutput
. Can you run the script below and see if it works?
<?php echo "<pre>"; $foo = new DOMDocument(); //$foo->preserveWhiteSpace = false; $foo->formatOutput = true; $root = $foo->createElement("root"); $root->setAttribute("attr", "that"); $bar = $foo->createElement("bar", "some text in bar"); $baz = $foo->createElement("baz", "some text in baz"); $foo->appendChild($root); $root->appendChild($bar); $root->appendChild($baz); echo htmlspecialchars($foo->saveXML()); echo "</pre>";?>