在修改domdocument结构时尝试格式化xml输出时,我遇到了奇怪的行为。
我已经基于DomDocument创建了简单的Item类:
class Item extends DOMDocument {
private $root;
function __construct($version = null, $encoding = null) {
parent::__construct($version, $encoding);
$this->formatOutput = true;
$this->root = $this->createElement("root");
$this->root = $this->appendChild($this->root);
}
function build($name) {
$item = $this->createElement("item");
$name = $this->createTextNode($name);
$item->appendChild($name);
$this->getElementsByTagName("root")->item(0)->appendChild($item);
}
}
现在,我的用例很小:
$it = new Item('1.0', 'iso-8859-1');
$it->build("first");
$it->build("seccond");
$xml = $it->saveXML();
echo $xml;
$it2 = new Item('1.0', 'iso-8859-1');
$it2->loadXML($xml);
$it2->build("third");
$it2->build("fourth");
$it2->build("fifth");
$it2->formatOutput = true;
$xml2 = $it2->saveXML();
echo $xml2;
现在奇怪的是。我调用脚本并根据需要生成两个xml文件,但是我注意到编辑文档后格式化已经丢失了。它有点继续没有任何缩进等。
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
<item>first</item>
<item>seccond</item>
</root>
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
<item>first</item>
<item>seccond</item>
<item>third</item><item>fourth</item><item>fifth</item></root>
我假设这是我在这里失踪的东西。也许这是我在打开文档后将节点附加到root的方式,也许是一些神奇的设置。
代码完成了这项工作,但我想知道造成这种奇怪行为的原因是什么。
答案 0 :(得分:2)
你可以“告诉”libxml前导/尾随空格不重要(因此在这种情况下,libxml可以插入空格来缩进元素),例如将preserveWhiteSpace属性设置为false。
$this->formatOutput = true;
$this->preserveWhiteSpace = false;
$this->root = $this->createElement("root");