Home » Php » xml – Is there a way to increase the indentation size of PHP's DOMDocument formatOutput property?

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

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.