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;
如果我在浏览器中打印它,我不会得到像这样的好XML结构
If I print it in the browser I don't get nice XML structure like
<xml> \n tab <child> etc.
我刚得到
<xml><child>ee</child></xml>
我想成为utf-8 这怎么可能呢?
And I want to be utf-8 How is this all possible to do?
推荐答案
您可以尝试执行以下操作:
You can try to do this:
...
// 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;
这可能更简洁.两种情况下的输出均为(演示):
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
更改缩进字符.您可以使用逐行正则表达式替换(例如,用 preg_replace
)对XML进行后处理:
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', "\t", $xml_string);
或者,有一个带有tidy_repair_string
的整洁扩展名,可以漂亮地打印XML数据也一样可以使用它指定缩进级别,但是整洁的将永远不会输出制表符.
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屋!