How to prevent self closing tag in php simplexml

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.


LIBXML_NOEMPTYTAG does not work with simplexml, per the spec:

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

To achieve what you're after, you need to convert the simplexml object to a DOMDocument object:

$xml = new SimpleXMLElement('<xml/>');
$child1 = $xml->addChild('child1');
$child1->addChild('child2', "value");
$child1->addChild('noValue', '');
$dom_sxe = dom_import_simplexml($xml);  // Returns a DomElement object

$dom_output = new DOMDocument('1.0');
$dom_output->formatOutput = true;
$dom_sxe = $dom_output->importNode($dom_sxe, true);
$dom_sxe = $dom_output->appendChild($dom_sxe);

echo $dom_output->saveXML($dom_output, LIBXML_NOEMPTYTAG);

which returns:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
  <child1>
    <child2>value</child2>
    <noValue></noValue>
  </child1>
</xml>

Something worth pointing out... the likely reason that the NOEMPTYTAG option is available for DOMDocument and not simplexml is that empty elements are not considered valid XML, while the DOM specification allows for them. You are banging your head against the wall to get invalid XML, which may suggest that the valid self-closing empty element would work just as well.


Since Simple XML is proving troublesome, perhaps XMLWriter could do what you want.

Here's a fiddle

<?php

$oXMLWriter = new XMLWriter;
$oXMLWriter->openMemory();
$oXMLWriter->startDocument('1.0', 'UTF-8');

$oXMLWriter->startElement('xml');
$oXMLWriter->writeElement('child1', 'Hello world!!');
$oXMLWriter->writeElement('noValue', '');
$oXMLWriter->endElement();

$oXMLWriter->endDocument();
echo htmlentities($oXMLWriter->outputMemory(TRUE));

?>

Output:

<?xml version="1.0" encoding="UTF-8"?>
  <xml>
    <child1>Hello world!!</child1>
    <noValue></noValue>
  </xml>

Tags:

Php

Xml

Simplexml