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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With