2011-12-23 123 views
41

這裏是代碼:PHP的XML如何輸出漂亮的格式

$doc = new DomDocument('1.0'); 
// create root node 
$root = $doc->createElement('root'); 
$root = $doc->appendChild($root); 
$signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df'); 
// process one row at a time 
foreach ($signed_values as $key => $val) { 
    // add node for each row 
    $occ = $doc->createElement('error'); 
    $occ = $root->appendChild($occ); 
    // add a child node for each field 
    foreach ($signed_values as $fieldname => $fieldvalue) { 
     $child = $doc->createElement($fieldname); 
     $child = $occ->appendChild($child); 
     $value = $doc->createTextNode($fieldvalue); 
     $value = $child->appendChild($value); 
    } 
} 
// get completed xml document 
$xml_string = $doc->saveXML() ; 
echo $xml_string; 

如果我在瀏覽器中打印我沒有得到很好的XML結構像

<xml> \n tab <child> etc. 

我只是得到

<xml><child>ee</child></xml> 

而且我想成爲utf-8 這是怎麼回事?

+0

關於您的UTF-8的問題,只是把它添加到對象,比如'$ DOC =新的DOM文檔( 「1.0」, 「UTF-8」)第二參數;' – Thielicious 2016-08-23 17:59:56

回答

73

你可以試着這樣做:

... 
// get completed xml document 
$doc->preserveWhiteSpace = false; 
$doc->formatOutput = true; 
$xml_string = $doc->saveXML(); 
echo $xml_string; 

您可以設置這些參數你所創建的DOMDocument之後還有:

$doc = new DomDocument('1.0'); 
$doc->preserveWhiteSpace = false; 
$doc->formatOutput = true; 

這可能是更簡潔。在這兩種情況下輸出是(Demo):

<?xml version="1.0"?> 
<root> 
    <error> 
    <a>eee</a> 
    <b>sd</b> 
    <c>df</c> 
    </error> 
    <error> 
    <a>eee</a> 
    <b>sd</b> 
    <c>df</c> 
    </error> 
    <error> 
    <a>eee</a> 
    <b>sd</b> 
    <c>df</c> 
    </error> 
</root> 

我不知道如何與DOMDocument改變縮進字符(S)。你可以後處理,XML與基於替換(例如,用preg_replace)的線由行正則表達式:

$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string); 

可替代地,還有就是tidy extension with tidy_repair_string這幾乎可以打印的XML數據,以及。可以使用它指定縮進級別,但整潔將永遠不會輸出製表符。這裏

tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]); 
+0

相關:[*調試DOMDocument對象在PHP *](http://stackoverflow.com/q/684227/367456)爲更受控制的形式的XML打印。 – hakre 2012-03-02 11:52:25

+0

相關:[*使用preg_replace轉換縮進(無回調)*](http://stackoverflow.com/q/8616594/367456) – hakre 2013-01-28 10:39:58

+0

我發現*「您可以在創建後立即設置這些參數DOMDocument以及「*不是一個好主意,如果您在處理/比較另一個文檔時使用'saveXML',因爲它會導致意外的結果。在需要輸出之前,最好格式化輸出。 – 2016-06-15 22:06:09

3

兩個不同的問題:

  • 設置formatOutputpreserveWhiteSpace屬性TRUE生成格式化XML:

    $doc->formatOutput = TRUE; 
    $doc->preserveWhiteSpace = TRUE; 
    
  • 許多Web瀏覽器(即Internet Explorer和Firefox)格式化XML時顯示它。使用查看源功能或常規文本編輯器檢查輸出。


參見xmlEncodingencoding

+1

'preserveWhiteSpace = TRUE'可以在你用'DOMDocument'漂亮地打印時得到你的方式 - 只是FYI,而不是有問題的例子,但是如果你從實際上有空白文本節點的現有文件加載。 – hakre 2011-12-24 02:23:56

+0

@hakre爲什麼'preserveWhiteSpace = TRUE'對XML工作正常,但不適用於HTML? – Yang 2014-11-07 21:15:10

+0

要讓瀏覽器對其進行格式化,必須設置適當的MIME類型。例如:whit: header('Content-type:text/xml'); – Den 2015-08-25 14:07:52

20

隨着SimpleXML對象,你可以簡單地

$domxml = new DOMDocument('1.0'); 
$domxml->preserveWhiteSpace = false; 
$domxml->formatOutput = true; 
/* @var $xml SimpleXMLElement */ 
$domxml->loadXML($xml->asXML()); 
$domxml->save($newfile); 

$xml是你的SimpleXML對象

,那麼你的SimpleXML可以保存爲通過$newfile

+0

您說SimpleXML,但您使用的是DOMDocument ... – quickshiftin 2015-02-09 05:08:36

+0

@quickshiftin - 輸入數據是'SimpleXMLElement'的一個實例。我將編輯答案以使其更加明顯。無論如何,我同意你給DOMDocument提供的東西實際上是不相關的。 – 2015-06-02 11:01:57

1

指定一個新的文件這是一個輕微上述主題的變化,但我在這裏以防其他人碰到這個,並且無法理解它......就像我做的那樣。

使用saveXML()時,目標DOMdocument中的preserveWhiteSpace不適用於導入的節點(如PHP 5.6)。

考慮下面的代碼:

$dom = new DOMDocument();        //create a document 
$dom->preserveWhiteSpace = false;      //disable whitespace preservation 
$dom->formatOutput = true;        //pretty print output 
$documentElement = $dom->createElement("Entry");  //create a node 
$dom->appendChild ($documentElement);     //append it 
$message = new DOMDocument();       //create another document 
$message->loadXML($messageXMLtext);      //populate the new document from XML text 
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document 
$documentElement->appendChild($node);     //append the new node to the document Element 
$dom->saveXML($dom->documentElement);     //print the original document 

在此背景下,$dom->saveXML();語句將不漂亮打印從$消息導入的內容,但原本在$ DOM內容將被美化打印。

爲了實現漂亮的印刷整個$ DOM文檔,該行:

$message->preserveWhiteSpace = false; 

必須包含$message = new DOMDocument();行之後 - 即。從中導入節點的文檔還必須具有preserveWhiteSpace = false。

9
<?php 

$xml = $argv[1]; 

$dom = new DOMDocument(); 

// Initial block (must before load xml string) 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
// End initial block 

$dom->loadXML($xml); 
$out = $dom->saveXML(); 

print_R($out); 
+1

你是否也可以添加解釋? – Robert 2016-01-11 10:59:34

+0

在載入xml字符串之前設置formatOutput = true&preserveWhiteSpace = false,否則它沒有任何作用---如果你能理解我的英文,哦,你是天才! – sigkill 2016-12-14 08:33:05

1
// ##### IN SUMMARY ##### 

$xmlFilepath = 'test.xml'; 
echoFormattedXML($xmlFilepath); 

/* 
* echo xml in source format 
*/ 
function echoFormattedXML($xmlFilepath) { 
    header('Content-Type: text/xml'); // to show source, not execute the xml 
    echo formatXML($xmlFilepath); // format the xml to make it readable 
} // echoFormattedXML 

/* 
* format xml so it can be easily read but will use more disk space 
*/ 
function formatXML($xmlFilepath) { 
    $loadxml = simplexml_load_file($xmlFilepath); 

    $dom = new DOMDocument('1.0'); 
    $dom->preserveWhiteSpace = false; 
    $dom->formatOutput = true; 
    $dom->loadXML($loadxml->asXML()); 
    $formatxml = new SimpleXMLElement($dom->saveXML()); 
    //$formatxml->saveXML("testF.xml"); // save as file 

    return $formatxml->saveXML(); 
} // formatXML 
+0

upvoted,因爲這個答案包含一個完整的例子! – baris1892 2018-03-04 08:19:28

0

嘗試了所有的答案,但沒有奏效。也許這是因爲我在保存XML之前追加和刪除了孩子。 經過大量的谷歌搜索發現this comment在PHP文檔。我只需重新加載生成的XML就可以工作。

$outXML = $xml->saveXML(); 
$xml = new DOMDocument(); 
$xml->preserveWhiteSpace = false; 
$xml->formatOutput = true; 
$xml->loadXML($outXML); 
$outXML = $xml->saveXML();