簡體   English   中英

PHP XML 如何 output 漂亮的格式

[英]PHP XML how to output nice format

以下是代碼:

$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 這怎么可能呢?

您可以嘗試這樣做:

...
// 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更改縮進字符。 您可以使用基於逐行正則表達式的替換(例如,使用preg_replace )對XML進行后處理:

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

另外,還有一個帶有tidy_repair_string整潔擴展名,它也可以漂亮地打印XML數據。 可以使用它指定縮進級別,但是整潔絕不會輸出制表符。

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

使用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指定的新文件

<?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);
// ##### 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

嘗試了所有答案,但沒有一個有效。 可能是因為我要在保存XML之前附加和刪除子級。 經過大量谷歌搜索后,在php文檔中找到了此注釋 我只需要重新加載生成的XML即可使其工作。

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

這里有兩個不同的問題:

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

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


另請參見xmlEncodingencoding

這是上述主題的細微變化,但我想將其放在此處,以防其他人碰到這個主題而無法理解它...就像我所做的那樣。

使用saveXML()時,目標DOM文檔中的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(); 語句不會很好地打印從$ message導入的內容,但是原來在$ dom中的內容將被漂亮地打印。

為了實現整個$ dom文檔的漂亮打印,該行:

$message->preserveWhiteSpace = false; 

必須包含在$message = new DOMDocument(); 線-即 導入節點的文檔還必須具有preserveWhiteSpace = false。

基於@heavenevil 的回答,這個 function 漂亮的打印使用瀏覽器

function prettyPrintXmlToBrowser(SimpleXMLElement $xml)
{
    $domXml = new DOMDocument('1.0');
    $domXml->preserveWhiteSpace = false;
    $domXml->formatOutput = true;
    $domXml->loadXML($xml->asXML());
    $xmlString = $domXml->saveXML();
    echo nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($xmlString)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM