5

I have an XML string that sometimes has empty nodes. When parsing this with simplexml_load_string the parser interprets any empty nodes (example <node></node>) to be an empty SimpleXMLElement. I actually would prefer these come through as an empty string, or are just omitted entirely.

I've tried using LIBXML_NOBLANKS as shown below, but it seems to have no effect. Here's some code that demonstrates the situation. the node "p2" is empty:

$xml = "<xml><p1>1</p1><p2></p2><p3>3</p3></xml>";

$obj = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOBLANKS);

header("Content-type: text/plain");

echo "STRING\n-----\n" . $xml;
echo "\n\nOBJ\n---\n" . print_r($obj,1);
echo "\n\nJSON\n----\n" . json_encode($obj);
4
  • I just made some tests and this does look like a bug in the XML module. Commented Aug 1, 2012 at 23:34
  • stackoverflow.com/questions/8603237/… Commented Aug 2, 2012 at 4:36
  • thanks for the replies. i have a hack solution involving converting to an array which is similar to the xpath solution, but I was hoping LIBXML_NOBLANKS or some other flag would handle it without having to enumerate. Commented Aug 2, 2012 at 17:53
  • 1
    @Jason you should have posted your solution Commented Jan 8, 2017 at 18:32

1 Answer 1

0

Here is working example for empty nodes:

    $nodes = $rootNode->xpath("//*[text()='']");
    foreach ($nodes as $node) {
        unset($node->{0});
    }

unset($node->{0}) - is a trick which destroyes this node and removes it from parent node.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.