PHP XML 如何输出漂亮的格式 [英] 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;
如果我在浏览器中打印它,我不会得到像
If I print it in the browser I don't get nice XML structure like
<xml>
tab <child> etc.
我刚好
<xml><child>ee</child></xml>
我想成为 utf-8这一切怎么可能?
And I want to be utf-8 How is this all possible to do?
推荐答案
您可以尝试这样做:
...
// get completed xml document
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml_string = $doc->saveXML();
echo $xml_string;
您也可以在创建 DOMDocument
后立即设置这些参数:
You can make set these parameter right after you've created the DOMDocument
as well:
$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
那可能更简洁.两种情况下的输出都是(Demo):
That's probably more concise. Output in both cases is (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
更改缩进字符.您可以使用基于逐行正则表达式的替换对 XML 进行后处理(例如使用 preg_replace
):
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
):
$xml_string = preg_replace('/(?:^|G) /um', " ", $xml_string);
或者,还有带有 tidy_repair_string
的 整洁扩展也可以漂亮地打印 XML 数据.可以用它指定缩进级别,但是 tidy 永远不会输出制表符.
Alternatively, there is the tidy extension with tidy_repair_string
which can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
这篇关于PHP XML 如何输出漂亮的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!