加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:34:06 所属栏目:PHP教程 来源:网络整理
导读:我想使用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 c
我想使用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,这可能表明有效的自我关闭的空元素也可以工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读