如何使用空白格式显示XML?

我有一个网页,它从应用更改的现有XML构建XML。我想在
textarea
中输出新的XML文件作为预览。它显示原始XML中存在的任何节点,其中包含原始XML很好的正确空格/格式(缩进和换行符),但任何新节点都显示在一行中没有缩进。例:
<original parent node>
    <original child>value</original child>
</original parent node>
<original parent node>
    <new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child>
</original parent node>
以下是在XML中写入和读回的代码:
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = true;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
file_put_contents($file, $dom->saveXML());
echo "<textarea cols='100' rows='40'>".file_get_contents($file)."</textarea>";
我也使用SimpleXML来操作XMLS。如何为新节点显示正确的whites间距?     
已邀请:
我发现
formatOutput
仅在
preserveWhiteSpace
被禁用时才有效:
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml);
echo $dom->saveXML();
    
加上这个,它对我有用。
echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
echo "<br/> <pre class="prettyprint" >". htmlentities($dom->saveXML($dom->firstChild->firstChild->firstChild))."</pre>"; 
您可以删除
$dom->firstChild->firstChild->firstChild
以获取更多信息。     
尝试:
echo "<textarea cols='100' rows='40'>".htmlspecialchars($xml->asXML())."</textarea>";
    

要回复问题请先登录注册