如何使用DomDocument编写XML自动关闭标签 [英] How to write XML self closing tag using DomDocument

查看:144
本文介绍了如何使用DomDocument编写XML自动关闭标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP生成XML,正在使用DomDocument生成XML标签,如何使用DomDocument创建自关闭标签?

I am working with PHP generate XML, I am using DomDocument to generate XML tags, How Can I created Self Closing Tag using DomDocument??

$doc2 = new DOMDocument();
$root2 = $doc2->createElement('root', '');

预期输出:

<?xml version="1.0"?><root/>

实际结果:

<?xml version="1.0"?><root></root>

还有其他方法可以生成自闭标签吗?

Is there any other way to generate Self-Closing Tag?

PS:请不要关闭问题,因为我不认为这是重复的。谢谢。

PS: Please don't close the Question as I don't think this is a duplicate. Thanks.

推荐答案

为createElement()提供空字符串的第二个参数会将一个空的textnode添加到元素节点。元素不为空,无法优化。

Providing the empty string second argument to createElement() adds an empty textnode to the element node. The element is not empty an can not be optimized. Without the argument DOM optimizes the XML.

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));
echo $dom->saveXml();

输出:

<?xml version="1.0"?>
<root/>

saveXml()的一个选项是避免优化。

Here is an option for saveXml() to avoid the optimization.

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));
echo $dom->saveXml(NULL, LIBXML_NOEMPTYTAG);

输出:

<?xml version="1.0"?>
<root></root>

这篇关于如何使用DomDocument编写XML自动关闭标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆