问题
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