Search code examples
phpxmlsimplexml

SimpleXML: do not expand self-closing tags


I have the problem with self-closing tags in SimpleXML. For example, my xml-file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<a>hello</a>
<b attr="1"/>
</root>

PHP code:

$xml = simplexml_load_file($path);
echo $xml->asXML();

Output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<a>hello</a>
<b attr="1"></b>
</root>

As you can see, SimpleXML converted self-closing tag <b attr="1"/> into <b attr="1"></b>. I do not need this. How to prevent this conversion?


Solution

  • Change the way you load the XML to

    $xml = simplexml_load_file($path, null, LIBXML_NOEMPTYTAG);
    

    This gives...

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <root>
    <a>hello</a>
    <b attr="1"/>
    </root>