Jos*_*zel 23 php xml whitespace indentation domdocument
我正在使用DOMDocument生成一个新的XML文件,我希望文件的输出很好地缩进,以便人类读者很容易理解.
例如,DOMDocument输出此数据时:
<?xml version="1.0"?>
<this attr="that"><foo>lkjalksjdlakjdlkasd</foo><foo>lkjlkasjlkajklajslk</foo></this>
我希望XML文件是:
<?xml version="1.0"?>
<this attr="that">
    <foo>lkjalksjdlakjdlkasd</foo>
    <foo>lkjlkasjlkajklajslk</foo>
</this>
我一直在寻找答案,我发现的所有内容似乎都试图以这种方式控制白色空间:
$foo = new DOMDocument();
$foo->preserveWhiteSpace = false;
$foo->formatOutput = true;
但这似乎没有做任何事情.也许这只适用于阅读XML?请记住,我正在尝试编写新文档.
有什么内置的DOMDocument可以做到这一点?或者可以轻松实现这一目标的功能?
小智 28
DomDocument会做的伎俩,我个人花了几个小时谷歌搜索并试图解决这个问题,我注意到如果你使用
$xmlDoc = new DOMDocument ();
$xmlDoc->loadXML ( $xml );
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->formatOutput = true;
$xmlDoc->save($xml_file);
按顺序,它只是不起作用,但如果您使用相同的代码,但按此顺序:
$xmlDoc = new DOMDocument ();
$xmlDoc->preserveWhiteSpace = false;
$xmlDoc->formatOutput = true;
$xmlDoc->loadXML ( $xml );
$xmlDoc->save($archivoxml);
像魅力一样,希望这会有所帮助
在得到John的一些帮助并自己玩这个之后,似乎即使DOMDocument对格式化的固有支持也不能满足我的需求.所以,我决定编写自己的缩进功能.
这是一个非常粗糙的功能,我刚刚快速拼凑在一起,所以如果有人有任何优化技巧或一般的任何说法,我会很高兴听到它!
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;
}
我尝试以不同的方式运行下面的设置代码formatOutput,preserveWhiteSpace唯一对输出有影响的成员是formatOutput. 你能运行下面的脚本看看它是否有效吗?
<?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>";
?>