46

标题基本概括了所有内容。

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

这对程序使用者来说很好,但对于调试/人工任务,有谁知道如何将它变成一个很好的缩进格式?

4

3 回答 3

79

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

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

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

于 2009-07-27T23:26:00.227 回答
62

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

$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
于 2013-04-29T15:19:02.517 回答
8

找到了一个类似的解决方案……格式化原始 xlm 数据……从我的php SOAP请求__getLastRequest & __getLastResponse中,为了快速调试 xml,我将它与google-code-prettify.

Its a good solution if you want to format sensitive xml data and don't want to do it online.

Some sample code below, may be helpful to others:

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($data); //=====$data has the raw xml data...you want to format

echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';

echo "<br/> <pre class=\"prettyprint\" >". htmlentities($dom->saveXML())."</pre>";

Below is a sample of the Formatted XML Output I got:

Note: The formatted XML is available in $dom->saveXML() and can be directly saved to a xml file using php file write.

Formatted XML Output

于 2015-10-07T07:29:20.177 回答