PHP XML 如何输出漂亮的格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8615422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 05:05:56  来源:igfitidea点击:

PHP XML how to output nice format

phpxmldomdocument

提问by Dakadaka

Here are the codes:

以下是代码:

$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;

If I print it in the browser I don't get nice XML structure like

如果我在浏览器中打印它,我不会得到很好的 XML 结构,例如

<xml> \n tab <child> etc.

I just get

我只是得到

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

And I want to be utf-8 How is this all possible to do?

我想成为 utf-8 这一切怎么可能?

回答by hakre

You can try to do this:

你可以尝试这样做:

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

You can make set these parameter right after you've created the DOMDocumentas well:

您也可以在创建后立即设置这些参数DOMDocument

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

That's probably more concise. Output in both cases is (Demo):

这可能更简洁。两种情况下的输出都是(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>

I'm not aware how to change the indentation character(s) with DOMDocument. You could post-process the XML with a line-by-line regular-expression based replacing (e.g. with preg_replace):

我不知道如何使用DOMDocument. 您可以使用基于逐行正则表达式的替换(例如 with preg_replace)对 XML 进行后处理:

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

Alternatively, there is the tidy extension with tidy_repair_stringwhich can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.

或者,还有一个tidy 扩展,tidy_repair_string它也可以漂亮地打印 XML 数据。可以使用它指定缩进级别,但是 tidy 永远不会输出制表符。

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

回答by heavenevil

With a SimpleXml object, you can simply

使用 SimpleXml 对象,您可以简单地

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

$xmlis your simplexml object

$xml是你的 simplexml 对象

So then you simpleXml can be saved as a new file specified by $newfile

那么你的 simpleXml 就可以保存为一个由指定的新文件 $newfile

回答by sigkill

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

回答by René

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

回答by Take

Tried all the answers but none worked. Maybe it's because I'm appending and removing childs before saving the XML. After a lot of googling found this commentin the php documentation. I only had to reload the resulting XML to make it work.

尝试了所有的答案,但没有一个奏效。也许是因为我在保存 XML 之前附加和删除了孩子。经过大量的谷歌搜索,在 php 文档中找到了这个评论。我只需要重新加载生成的 XML 即可使其工作。

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

回答by álvaro González

Two different issues here:

这里有两个不同的问题:

  • Set the formatOutputand preserveWhiteSpaceattributes to TRUEto 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.

  • formatOutputpreserveWhiteSpace属性设置TRUE为生成格式化的 XML:

    $doc->formatOutput = TRUE;
    $doc->preserveWhiteSpace = TRUE;
    
  • 许多 Web 浏览器(即 Internet Explorer 和 Firefox)在显示 XML 时会对其进行格式化。使用查看源功能或常规文本编辑器来检查输出。



See also xmlEncodingand encoding.

另请参阅xmlEncodingencoding

回答by Pancho

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

这是上述主题的一个轻微变化,但我把它放在这里以防其他人遇到这个并且无法理解它......就像我一样。

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

使用 saveXML() 时,目标 DOMdocument 中的 preserveWhiteSpace 不适用于导入的节点(如 PHP 5.6)。

Consider the following code:

考虑以下代码:

$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

In this context, the $dom->saveXML();statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

在这种情况下,该$dom->saveXML();语句不会漂亮地打印从 $message 导入的内容,但最初在 $dom 中的内容将被漂亮地打印出来。

In order to achieve pretty printing for the entire $dom document, the line:

为了实现整个 $dom 文档的漂亮打印,该行:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument();line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

必须包含在该$message = new DOMDocument();行之后 - 即。从中导入节点的文档也必须有preserveWhiteSpace = false。