开发者

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

开发者 https://www.devze.com 2023-01-28 01:41 出处:网络
Is there a way to increase the indentation size of PHP\'s 开发者_Go百科DOMDocument formatOutput property?Right now it indents each node 2 spaces.I would like to make it either a tab or 4 spaces.This i

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消