Turn OFF self-closing tags in SimpleXML for PHP?

放肆的年华 提交于 2019-12-23 21:26:31

问题


I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:

$doc->addChild('myToken');

This generates (what I know as) a self-closing or single tag:

<myToken/>

However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:

<myToken></myToken>

The question is, how do I do this, outside of running the generated XML through a preg_replace?


回答1:


From the documentation at SimpleXMLElement->__construct and LibXML Predefined Constants, I think this should work:

<?php
$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);

// some processing here

$out = $sxe->asXML();
?>

Try that and see if it works. Otherwise, I'm afraid, it's preg_replace-land.




回答2:


At the moment, it is not possible to avoid self closing tags wiht LibXML. One of the proposed solution by @Piskvor will not work:

LIBXML_NOEMPTYTAG does not work with simplexml, as mentionned here:

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

A workaround for that will be to use the answer from this question




回答3:


If you set the value to something empty (i.e. null, empty string) it will use open/close brackets.

$tag = '<SomeTagName/>';

echo "Tag: '$tag'\n\n";

$x = new SimpleXMLElement($tag);
echo "Autoclosed: {$x->asXML()}\n";

$x = new SimpleXMLElement($tag);
$x[0] = null;
echo "Null: {$x->asXML()}\n";

$x = new SimpleXMLElement($tag);
$x[0] = '';
echo "Empty: {$x->asXML()}\n";

See example: http://sandbox.onlinephpfunctions.com/code/10642a84dca5a50eba882a347f152fc480bc47b5




回答4:


May be not the best solution but got same problem and solved it with using pre_replace to change all the self closing tags to full form...

$xml_reader = new XMLReader;
$xml_reader->open($xml_file);

$data = preg_replace('/\<(\w+)\s*\/\s*\>/i', '<$1></$1>', $xml_reader->readOuterXML());



回答5:


LIBXML_NOEMPTYTAG works but only if you use DOMDocument::save or DOMDocument::saveXML

$dom = dom_import_simplexml(SimpleXMLElement)->ownerDocument;
$dom->formatOutput = true;
$dom->save($save_path, LIBXML_NOEMPTYTAG);


来源:https://stackoverflow.com/questions/259719/turn-off-self-closing-tags-in-simplexml-for-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!