Self-closing tags using createElement

I need to add a self-closing tag to the XML file with the DOM in PHP, but I don’t know how to do it, because by default this tag looks like this:

<tag></tag>

But it should look like this:

<tag/>
+5
source share
2 answers

DOM will do it automatically for you

$dom = new DOMDocument;
$dom->appendChild($dom->createElement('foo'));
echo $dom->saveXml();

will give default

<?xml version="1.0"?>
<foo/>

if you do not

$dom = new DOMDocument;
$dom->appendChild($dom->createElement('foo'));
echo $dom->saveXml($dom, LIBXML_NOEMPTYTAG);

which would then give

<?xml version="1.0" encoding="UTF-8"?>
<foo></foo>
+13
source

Just pass a parameter node DOMDocument::saveXMLto only print a specific node, without an XML declaration:

$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = false;
$node = $doc->createElement('foo');

// Trimming the default carriage return char from output
echo trim($doc->saveXML($node)); 

will give

<foo/>

not containing any newline / carriage return char.

0
source

All Articles