Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SimpleXML::addChild with empty string - redundant node

Calling addChild with an empty string as the value (or even with whitespace) seems to cause a redundant SimpleXml node to be added inside the node instead of adding just the node with no value.

Here's a quick demo of what happens:

[description] => !4jh5jh1uio4jh5ij14j34io5j!

And here's with an empty string:

[description] => SimpleXMLElement Object ( [0] => ) 

The workaround I'm using at the moment is pretty horrible - I'm doing a str_replace on the final JSON to replace !4jh5jh1uio4jh5ij14j34io5j! with an empty string. Yuck. Perhaps the only answer at this point is 'submit a bug report to simplexml'...

Does anyone have a better solution?

like image 881
Dave Avatar asked Mar 20 '26 21:03

Dave


1 Answers

I think I figured out what is going on. Given code like this:

$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node','value');
print_r($xml);

$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node','');
print_r($xml);

$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node');
print_r($xml);

The output is this:

SimpleXMLElement Object
(
    [node] => value
)
SimpleXMLElement Object
(
    [node] => SimpleXMLElement Object
        (
            [0] => 
        )

)
SimpleXMLElement Object
(
    [node] => SimpleXMLElement Object
        (
        )

)

So, to make it so that in case #2 the empty element isn't created (i.e. if you don't know if the second argument is going to be an empty string or not), you could just do something like this:

$mystery_string = '';

$xml = new SimpleXMLElement('<xml></xml>');
if (preg_match('#\S#', $mystery_string)) // Checks for non-whitespace character
  $xml->addChild('node', $mystery_string);
else
  $xml->addChild('node');

print_r($xml);
echo "\nOr in JSON:\n";
echo json_encode($xml);

To output:

SimpleXMLElement Object
(
    [node] => SimpleXMLElement Object
        (
        )

)

Or in JSON:
{"node":{}}

Is that what you want?

Personally, I never use SimpleXML, and not only because of this sort of weird behavior -- it is still under major development and in PHP5 is missing like 2/3 of the methods you need to do DOM manipulation (like deleteChild, replaceChild etc).

I use DOMDocument (which is standardized, fast and feature-complete, since it's an interface to libxml2).

like image 170
joelhardi Avatar answered Mar 23 '26 10:03

joelhardi