PHP SimpleXML :: addChild with empty string - redundant node

Calling addChild with an empty string as the value (or even with a space) seems to cause adding the excess SimpleXml node inside the node instead of adding only the node without the value.

Here is a brief description of what is happening:

[description] => !4jh5jh1uio4jh5ij14j34io5j!

And here with an empty line:

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

The workaround I'm currently using is pretty awful - I'm doing str_replace on the last JSON to replace! 4jh5jh1uio4jh5ij14j34io5j! with an empty string. Ugh. Perhaps the only answer at this point is "send a bug report in simplexml" ...

Does anyone have a better solution?

+3
source share
4 answers

I think I understood what was happening. This code is as follows:

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

Conclusion:

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

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

)

, , №2 (.. , ), - :

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

:

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

)

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

, ?

SimpleXML, - - , PHP5 , 2/3 , DOM (, deleteChild, replaceChild ..).

DOMDocument ( , , libxml2).

+1

SimpleXML , , print_r() var_dump(), serialize() , , . "" , PHP .

AsXML().

- print_r() SimpleXML → , . , "echo $xml- > surname" $xml- > names [1], , XML, : munged , , PHP (, "var" ), , $xml [ "var" ] - , , , . -, - . AsXML() .

+1

, , , addChild, node, , node. ( ) , node.

, .

0

Xml, simpleXml, , DOMDocument, SimpleXml ( libxml2 - by ). , AsArray() AsJson() .

I just updated the library to work as you expect when releasing JSON. You can do the following:

$xml = new bXml('<xml></xml>');
$xml->addChild('node', '');
$json_w_root = $xml->asJson(); // is { 'xml': {'node':'' } }
$json = $xml->children()->asJson(); // is { 'node' : '' } as expected.

The library is hosted in google code http://code.google.com/p/blibrary/

0
source

Source: https://habr.com/ru/post/1698876/


All Articles