花了一些時間搜尋才找出這個問題。到目前為止,我沒在手冊中看到太多關於這個小問題的解釋。(對於 PHP5,我相信)
當 DOM 的來源來自透過 load() 從檔案載入時,formatOutput = true; 似乎會失敗。例如
<?php
$dom = new DOMDocument();
$dom->load ("test.xml");
$dom->formatOutput = true;
$new_tag = $dom->createElement ('testNode');
$new_tag->appendChild (
$dom->createElement ('test', 'this is a test'));
$dom->documentElement->appendChild ($new_tag);
printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>
不會縮排輸出,並會將修改過的節點全部顯示在一長行中。當儲存到檔案時,會使編輯 config.xml 有點困難。
在 load() 之前加入 preserveWhiteSpace = false;,formatOutput 就能如預期運作。例如
<?php
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->load ("test.xml");
$dom->formatOutput = true;
$new_tag = $dom->createElement ('testNode');
$new_tag->appendChild (
$dom->createElement ('test', 'this is a test'));
$dom->documentElement->appendChild ($new_tag);
printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>
注意:如果你的載入的 XML 檔案 (test.xml) 有一個空的根節點,且該節點沒有被縮短或沒有子節點,這將無法運作。
範例
無法運作
<?xml version="1.0"?>
<root>
</root>
可以運作
<?xml version="1.0"?>
<root/>
可以運作
<?xml version="1.0"?>
<root>
<!-- 註解 -->
</root>
可以運作
<?xml version="1.0"?>
<root>
<child/>
</root>