SimpleXML::addChild() 输出到 xml 时无法添加换行符
<?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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SimpleXML 扩展仅限于格式化输出,它的姊妹扩展 DOMDocument 支持输出格式。示例中的 XML 字符串并使用
DOMDocument::$preserveWhiteSpace
和DOMDocument::$formatOutput
来控制格式:这将输出带有换行符的良好缩进的 XML您要求的地方:
如果您进一步需要操作缩进,您可以使用相关问题和答案中概述的正则表达式:使用 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
andDOMDocument::$formatOutput
to control the formatttings:This will output a nicely indented XML with the linebreaks where you have asked for them:
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.