开发者

Self-closing tags using createElement

开发者 https://www.devze.com 2023-04-06 23:42 出处:网络
I need to add a self-closing tag to XML file with DOM in PHP, but I don\'t know how, because standardly, this tag looks like this:

I need to add a self-closing tag to XML file with DOM in PHP, but I don't know how, because standardly, this tag looks like this:

<tag></tag>
开发者_StackOverflow

But it should look like this:

<tag/>


DOM will do that automatically for you

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

will give by default

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

unless you do

$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>


Just pass a node param to DOMDocument::saveXML in order to output only a specific node, without any 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 new line / carriage return ending char.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号