如何防止php simplexml中的自动关闭标签

我想使用PHP simplexml生成xml.
$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>

我想要的是如果标签没有价值,应该显示这样

<novalue></novalue>

我试过从Turn OFF self-closing tags in SimpleXML for PHP?使用LIBXML_NOEMPTYTAG

我试过$xml = new SimpleXMLElement(‘< xml />‘,LIBXML_NOEMPTYTAG);它不行.所以我不知道把LIBXML_NOEMPTYTAG放在哪里

根据 spec,LIBXML_NOEMPTYTAG不适用于simplexml:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

为了实现你以后的目标,你需要将simplexml对象转换成一个DOMDocument对象:

$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,这可能表明有效的自我关闭的空元素也可以工作.

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...