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

2022-08-30 10:47:59

标题几乎说明了一切。

如果我有类似的东西(来自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>

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


答案 1

在 SimpleXMLElement 的 PHP 手册页上的评论中有各种解决方案。不是很有效,但肯定很简洁,是Anonymous的解决方案

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

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


答案 2

以上对我不起作用,我发现这有效:

$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();

推荐