Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to increase the indentation size of PHP's DOMDocument formatOutput property?

Is there a way to increase the indentation size of PHP's DOMDocument formatOutput property? Right now it indents each node 2 spaces. I would like to make it either a tab or 4 spaces.

like image 936
ThinkingInBits Avatar asked Dec 03 '10 20:12

ThinkingInBits


2 Answers

This isn't a very nice solution because it depends on knowing that the format is prefixed with double spaces:

preg_replace_callback('/^( +)</m', function($a) { 
  return str_repeat(' ',intval(strlen($a[1]) / 2) * 4).'<';  
}, $doc->saveXML());

It replaces each indentation with 4 spaces. Or you could remove the *4 and use "\n" as the repeating character.

like image 148
Matthew Avatar answered Sep 22 '22 20:09

Matthew


It might be possible to change the indentation string in libxml, but to my knowledge you cannot alter the indentation DOM uses. It's possible for XMLWriter though.

As an alternative, you could use Tidy to prettyprint the XML:

$dom = new DOMDocument;
$dom->preserveWhiteSpace = TRUE;
$dom->loadXml('<root><foo><bar>   baz   </bar></foo></root>');
$tidy = tidy_parse_string($dom->saveXml(), array(
    'indent' => TRUE,
    'input-xml' => TRUE,
    'output-xml' => TRUE,
    'add-xml-space' => FALSE,
    'indent-spaces' => 4
));
$tidy->cleanRepair();
echo $tidy;

but note that this behaves quirky in the above case. It removes the spaces in the bar element unless you slap an xml:space="preserve" on the bar tag. When you do that it will keep the spaces but also put newlines before and after. You have to fiddle with it to see if it fits your problem. See Tidy docs

like image 21
Gordon Avatar answered Sep 24 '22 20:09

Gordon