PHP SimpleXML, empty node and CDATA

Php is a great language, but sometimes I come across these little carelessness or superficiality in implementing some of its core libraries.

UPDATE 21-04-2012: another problem is that I can't serialize SimpleXML object (ie in the session variable it generate this error "session_start() [function.session-start]: Node no longer exists")

Now the problem is how SimpleXML treat the empty node. If I've this php code:

$xmlIdentify = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
          <PatronIdentify>
                    <Username></Username>
                    <Password></Password>
                    <Msg></Msg>
            </PatronIdentify>
EOF;
$identify = new SimpleXMLElement($xmlIdentify);
$identify->Username[0] = 'myusername';
$identify->Password[0] = 'mypwd';
echo $identify->asXML(); 

The xml echoed change this:
<Msg></Msg>
to:
<Msg/> 
There is LIBXML_NOEMPTYTAG, a libxml option to change this behavior, but it works only with  DOMDocument::save and DOMDocument::saveXML functions.

Another problem is how SimpleXML manage CDATA, but you can use LIBXML_NOCDATA to force SimpleXML to store it like string, in this manner:
$identify = new SimpleXMLElement($xmlIdentify, LIBXML_NOCDATA);
Without this option you have to cast object to string, like this:
$username = (string) $identify->Username[0];
If you need to combine two or more options, you can use pipe:
 $identify = new SimpleXMLElement($xmlIdentify, LIBXML_NOEMPTYTAG | LIBXML_NOCDATA);

Commenti