【问题标题】:How can I display XML with whitespace formatting?如何使用空格格式显示 XML?
【发布时间】:2010-12-21 23:08:43
【问题描述】:

我有一个网页,它通过应用更改的现有 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。如何为新节点显示正确的空白?

【问题讨论】:

  • 哇。 loadXML/asXML、file_put_contents/file_get_contents... 这应该有什么用?相关:$xml 是什么?

标签: php xml formatting simplexml whitespace


【解决方案1】:

我发现formatOutput 仅在preserveWhiteSpace 被禁用时才有效:

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml);
echo $dom->saveXML();

【讨论】:

  • 伙计们,我被困在第 4 行,因为它给了我一个错误:注意:未定义的变量:第 88 行 C:\wamp\www\3ace\index.php 中的 xml
【解决方案2】:

添加这个,它对我有用。

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-&gt;firstChild-&gt;firstChild-&gt;firstChild以获取更多信息。

【讨论】:

    【解决方案3】:

    试试:

    echo "<textarea cols='100' rows='40'>".htmlspecialchars($xml->asXML())."</textarea>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      相关资源
      最近更新 更多