SimpleXML::addChild() 输出到 xml 时无法添加换行符

发布于 2024-09-24 19:30:03 字数 492 浏览 0 评论 0原文

<?xml version="1.0" encoding="utf-8"?><items>
<item><title>title3</title><desc>This is some desc3</desc></item></items>

使用asXML()输出时各个节点元素之间没有换行?

如何通过在每个包含子元素节点的 XML 元素开始和结束标记后添加换行符来使输出文件结构良好:

<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<title>title3</title>
<desc>This is some desc3</desc>
</item>
</items>
<?xml version="1.0" encoding="utf-8"?><items>
<item><title>title3</title><desc>This is some desc3</desc></item></items>

There is no line break between each node element when using asXML() to output?

How to make output the file well-structured by adding a line break after each XML elements opening and closing tag that contains child element nodes:

<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<title>title3</title>
<desc>This is some desc3</desc>
</item>
</items>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哑剧 2024-10-01 19:30:03

SimpleXML 扩展仅限于格式化输出,它的姊妹扩展 DOMDocument 支持输出格式。示例中的 XML 字符串并使用 DOMDocument::$preserveWhiteSpaceDOMDocument::$formatOutput 来控制格式:

$doc = new DOMDocument();

$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$doc->loadXML($string);

echo $doc->saveXML();

这将输出带有换行符的良好缩进的 XML您要求的地方:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
    <title>title3</title>
    <desc>This is some desc3</desc>
  </item>
  <empty/>
</items>

如果您进一步需要操作缩进,您可以使用相关问题和答案中概述的正则表达式:使用 preg_replace 转换缩进(无回调)

如果您不想使用该方法,您也可以从 SimpleXML 切换到其他方法,然后切换到 XMLWriter,它提供了设置缩进的方法(XMLWriter::setIndent) 打印的 XML。您需要找到 XML 模型的临时表示,以便使用 XMLWriter 编写它,但这看起来并不那么简单。

The SimpleXML extension is limited to format the output, it's sister extension, DOMDocument has support for output formatting. The XML string from your example and making use of DOMDocument::$preserveWhiteSpace and DOMDocument::$formatOutput to control the formatttings:

$doc = new DOMDocument();

$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;

$doc->loadXML($string);

echo $doc->saveXML();

This will output a nicely indented XML with the linebreaks where you have asked for them:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <item>
    <title>title3</title>
    <desc>This is some desc3</desc>
  </item>
  <empty/>
</items>

If you further need to manipulate the indent, you can make use of regular expressions which has been outlined in a related question and answer: Converting indentation with preg_replace (no callback).

If you don't want to use that method you could also switch from SimpleXML to something else and then to XMLWriter which provides a method to set the indentation (XMLWriter::setIndent) of printed XML. You would need to find an interim representation of your XML model to write it with XMLWriter however which does not look that trivial.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文