php - $SimpleXML->asXML() 的格式输出;

标题几乎说明了一切。

如果我有类似的东西(来自 PHP 站点示例):

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies></movies>
XML;

$sxe = new SimpleXMLElement($xmlstr);

$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character  = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');


echo("<pre>".htmlspecialchars($sxe->asXML())."</pre>");

die();

我最终会像这样输出一个长字符串:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary"><movie><title>PHP2: More Parser Stories</title><plot>This is all about the people who make it work.</plot><characters><character><name>Mr. Parser</name><actor>John Doe</actor></character></characters><rating type="stars">5</rating></movie></movies>

这对于程序使用者来说很好,但对于调试/人工任务,有谁知道如何将其转换为良好的缩进格式?

最佳答案

PHP manual page for SimpleXMLElement 的评论中有多种解决方案.不是很有效,但肯定很简洁,是 Anonymous 的解决方案

$dom = dom_import_simplexml($simpleXml)->ownerDocument;
$dom->formatOutput = true;
echo $dom->saveXML();

PHP 手册页注释通常是满足常见需求的好来源,只要您先过滤掉明显错误的内容。

关于php - $SimpleXML->asXML() 的格式输出;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1191167/

相关文章:

c++ - 使用printf打印 float 时有额外的前导零?

c# - 在 C# 中使用自定义千位分隔符

c# - 十六进制的 String.Format

c# - 在 C# (asp.net MVC3) 中用逗号和小数格式化数字

ios - 如何将 Double 格式化为货币 - Swift 3

c# - 格式化 TimeSpan 大于 24 小时

c# - 如何停止 ReSharper 删除对象初始化程序中的空格

ruby - CSV.read 第 x 行的非法引用

excel - (Excel) 基于相邻单元格值的条件格式

python - 如何右对齐数字数据?