2010-07-29 69 views
2

我使用php domdocument將數據插入到xml文件中。然而,當我打開xml文件,數據顯示在一行:對齊xml文檔

<?xml version="1.0"?> 
<root><activity>swimming</activity><activity>jogging</activity></root> 

我該如何以編程方式對齊它?

<?xml version="1.0"?> 
<root> 
    <activity>swimming</activity> 
    <activity>jogging</activity> 
</root> 

回答

6

您可以使用此功能

 
function pretty_xml($string) { 
    $xml = DOMDocument::loadXML($string); 
    $xml->formatOutput = true; 
    return $xml->saveXML(); 
} 
+0

我在哪裏調用這個函數? – input 2010-07-29 13:17:10

+0

在您將xml發送到瀏覽器之前,請將其置於此位置。如果你已經使用$ xml-> saveXML()(從domdocument)來輸出xml,那麼就把$ your_document-> formatOutput = true;在發送XML到瀏覽器之前。 – jcubic 2010-07-29 13:26:23

+0

這裏的重要特性,就像jcubic的最後一條評論所暗示的,是DOMDocument的'$ formatOutput'屬性,它可以在創建對象後的任何時候設置(即,您不必在用戶函數中使用它。請參閱DOMDocument的文檔。) – GZipp 2010-07-29 13:31:21

1

使用換行符和標籤分別爲 「\ n」 和 「\ t」 的,在你的PHP代碼中使用雙引號。

+0

試過。當我點擊輸入插入數據時,頁面變爲空白而不是顯示數據。並在xml文件中創建節點時,它們是空的。 – input 2010-07-29 13:22:35