2010-08-27 59 views
1

當我嘗試在修改domdocument結構時嘗試格式化xml輸出時,我遇到了奇怪的行爲。php domdocument奇怪的格式化

我已經創建了一個基於的DomDocument簡單的項目類:

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> 

我假設這是我在這裏失蹤的東西。也許這是我打開文檔後將節點附加到根節點的方式,也許是一些魔術設置。

該代碼完成這項工作,但我想知道這種奇怪行爲的原因是什麼。

回答

2

您可以「告訴」libxml前導/尾隨空格不重要(因此在這種情況下,libxml可以將空格插入縮進元素),例如通過將preserveWhiteSpace屬性設置爲false。

$this->formatOutput = true; 
$this->preserveWhiteSpace = false; 
$this->root = $this->createElement("root"); 
+0

我知道這將是簡單的事情:) 謝謝,它是有道理的,並按預期工作。 – Greg 2010-08-27 11:25:35