PHP如何输出格式良好的XML?

83

以下是代码:

$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编码,如何实现呢?


1
关于你的UTF-8问题,只需将其作为第二个参数添加到对象中,如 $doc = new DOMDocument("1.0", "UTF-8"); - Thielicious
8个回答

127
您可以尝试这样做:

您可以尝试以下操作:

...
// 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;

这可能更加简洁。在两种情况下的输出结果是(演示):

<?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更改缩进字符。您可以使用基于逐行正则表达式替换的XML后处理(例如使用preg_replace):

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

另外,还有一个tidy扩展和tidy_repair_string可将XML数据进行漂亮的打印。它可以指定缩进级别,但是tidy永远不会输出制表符。

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

相关:在 PHP 中调试 DOMDocument 对象,以实现更受控制的 XML 打印形式。 - hakre
我发现如果你使用saveXML对比另一个文档时,若在创建DOMDocument后立即设置这些参数可能会导致意料之外的结果。最好在需要输出前格式化输出。 - Jeff Puckett

39

通过一个 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 指定的新文件。


@quickshiftin - 输入数据是SimpleXMLElement的实例。我会编辑答案,以使其更加明显。无论如何,我同意您输入到DOMDocument中的内容实际上是无关紧要的。 - Álvaro González
此外,在 loadXML 之后 save 之前,您可以使用 $domxml->encoding = "UTF-8" - user1742529

24
<?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);

4
你能否也加上解释? - Robert

12

尝试了所有答案,但都没有成功。也许是因为在保存XML之前,我正在添加和删除子元素。 经过大量的搜索,在php文档中找到了这个评论。我只需要重新加载生成的XML就可以使它工作。

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

6
// ##### 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

因为这个答案包含了一个完整的示例,所以我点了赞! - baris1892
非常好的答案,这是我在处理RSS XML时唯一完全可行的选项。 - Kevinleary.net

4

这里有两个不同的问题:

  • Set the formatOutput and preserveWhiteSpace attributes to TRUE to generate formatted XML:

    $doc->formatOutput = TRUE;
    $doc->preserveWhiteSpace = TRUE;
    
  • Many web browsers (namely Internet Explorer and Firefox) format XML when they display it. Use either the View Source feature or a regular text editor to inspect the output.


还可参考xmlEncodingencoding


1
当您使用DOMDocument进行漂亮的打印时,preserveWhiteSpace = TRUE可能会妨碍您 - 这只是提醒,并不适用于问题中给出的示例,但如果您从实际包含空格文本节点的现有文件加载,则会出现此情况。 - hakre
@hakre为什么在XML中使用preserveWhiteSpace = TRUE可以正常工作,但在HTML中却无法正常工作? - Yang
为了让浏览器格式化它,必须设置适当的 MIME 类型。例如: header('Content-type: text/xml'); - Den
我实际上需要看到空格,所以这对我来说是正确的答案。 - gog

2

这是与上面主题略有不同的一个变体,但我把它放在这里,以防其他人遇到此类问题,无法理解它...就像我一样。

在使用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();语句不会对从$message导入的内容进行漂亮打印,但是$dom中原有的内容将被漂亮打印。
为了使整个$dom文档漂亮打印,需要添加以下代码行:
$message->preserveWhiteSpace = false; 

必须在$message = new DOMDocument();行之后包含 - 也就是导入节点的文档必须同样具有preserveWhiteSpace = false属性。


0
基于@heavenevil的答案,此函数使用浏览器进行漂亮的打印。
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)));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接