如何防止PHP SimpleXML中的自闭标签 [英] How to prevent self closing tag in php simplexml
问题描述
我想使用php simplexml生成xml.
I want to generate xml by using php simplexml.
$xml = new SimpleXMLElement('<xml/>');
$output = $xml->addChild('child1');
$output->addChild('child2', "value");
$output->addChild('noValue', '');
Header('Content-type: text/xml');
print($xml->asXML());
输出为
<xml>
<child1>
<child2>value</child2>
<noValue/>
</child1>
</xml>
我想要的是,如果标签没有值,它应该像这样显示
What I want is if the tag has no value it should display like this
<noValue></noValue>
我尝试使用中的LIBXML_NOEMPTYTAG
关闭用于PHP的SimpleXML中的自动关闭标签?
I've tried using LIBXML_NOEMPTYTAG
from Turn OFF self-closing tags in SimpleXML for PHP?
我已经尝试过$xml = new SimpleXMLElement('<xml/>', LIBXML_NOEMPTYTAG);
,但是它不起作用.所以我不知道将LIBXML_NOEMPTYTAG
I've tried $xml = new SimpleXMLElement('<xml/>', LIBXML_NOEMPTYTAG);
and it doesn't work. So I don't know where to put the LIBXML_NOEMPTYTAG
推荐答案
LIBXML_NOEMPTYTAG
不适用于simplexml,根据
LIBXML_NOEMPTYTAG
does not work with simplexml, per the spec:
此选项当前仅在DOMDocument :: save和DOMDocument :: saveXML函数中可用.
This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.
要实现目标,您需要将simplexml对象转换为DOMDocument对象:
To achieve what you're after, you need to convert the simplexml object to a DOMDocument object:
$xml = new SimpleXMLElement('<xml/>');
$child1 = $xml->addChild('child1');
$child1->addChild('child2', "value");
$child1->addChild('noValue', '');
$dom_sxe = dom_import_simplexml($xml); // Returns a DomElement object
$dom_output = new DOMDocument('1.0');
$dom_output->formatOutput = true;
$dom_sxe = $dom_output->importNode($dom_sxe, true);
$dom_sxe = $dom_output->appendChild($dom_sxe);
echo $dom_output->saveXML($dom_output, LIBXML_NOEMPTYTAG);
返回:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<child1>
<child2>value</child2>
<noValue></noValue>
</child1>
</xml>
值得指出的是... NOEMPTYTAG选项可用于DOMDocument而不是simplexml的可能原因是空元素不被视为有效的XML,而DOM规范允许它们.您将头撞在墙上以获取无效的XML,这可能表明有效的自动关闭空元素也将正常工作.
Something worth pointing out... the likely reason that the NOEMPTYTAG option is available for DOMDocument and not simplexml is that empty elements are not considered valid XML, while the DOM specification allows for them. You are banging your head against the wall to get invalid XML, which may suggest that the valid self-closing empty element would work just as well.
这篇关于如何防止PHP SimpleXML中的自闭标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!