Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn OFF self-closing tags in SimpleXML for PHP?

Tags:

php

xml

simplexml

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?

like image 552
TimTowdi Avatar asked Jan 24 '23 00:01

TimTowdi


2 Answers

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.

like image 166
Piskvor left the building Avatar answered Jan 26 '23 14:01

Piskvor left the building


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

like image 44
drzaus Avatar answered Jan 26 '23 13:01

drzaus