I want to generate xml by using php simplexml.
$xml = new SimpleXMLElement('<xml/>');
$output = $xml->addChild('child1');
$output->addChild('child2', "value");
$output->addChild('noValue', '');
Header('Content-type: text/xml');
print($xml->asXML());
The output is
<xml>
<child1>
<child2>value</child2>
<noValue/>
</child1>
</xml>
What I want is if the tag has no value it should display like this
<noValue></noValue>
I've tried using LIBXML_NOEMPTYTAG
from Turn OFF self-closing tags in SimpleXML for PHP?
I've tried $xml = new SimpleXMLElement('<xml/>', LIBXML_NOEMPTYTAG);
and it doesn't work. So I don't know where to put the LIBXML_NOEMPTYTAG
There are also tags that are forbidden to be closed: img, input, br, hr, meta, etc.
A self-closing tag is an element of HTML code that has evolved in the language. Typically, the self-closing tag makes use of a “/” character in order to effectively close out a beginning tag enclosed in sideways carets.
Self Closing HTML ElementsThe br tag inserts a line break (not a paragraph break). This tag has no content, so it is self closing.
The fact is there is no need to close self closing tags by a slash /> at the end of the tag. Although many people use it but there is no meaning of slash at the end of the start tag even though you use it is ignored by the browsers.
Despite the quite lengthy answers already given - which are not particularly wrong and do shed some light into some libxml library internals and it's PHP binding - you're most likely looking for:
$output->noValue = '';
To add an open tag, empty node-value and end tag (beautified, demo is here: http://3v4l.org/S2PKc):
<?xml version="1.0"?>
<xml>
<child1>
<child2>value</child2>
<noValue></noValue>
</child1>
</xml>
Just noting as it seems it has been overlooked with the existing answers.
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