如何使用DomDocument编写XML自闭标记

时间:2022-10-27 07:52:37

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

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

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

Expected Output:

预期的输出:

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

Actual result:

实际结果:

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

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

有没有其他方法来生成自闭标签?

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

请不要结束这个问题,因为我不认为这是重复的。谢谢。

1 个解决方案

#1


4  

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.

向createElement()提供空字符串second参数将空textnode添加到元素节点。元素不是空的,不能优化。没有参数DOM优化XML。

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

Output:

输出:

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

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

这里是saveXml()的一个选项,以避免优化。

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

Output:

输出:

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

#1


4  

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.

向createElement()提供空字符串second参数将空textnode添加到元素节点。元素不是空的,不能优化。没有参数DOM优化XML。

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

Output:

输出:

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

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

这里是saveXml()的一个选项,以避免优化。

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

Output:

输出:

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