phpsimplexml

Why does a SimpleXML object evaluates to boolean TRUE?


I am a newcomer to PHP and SimpleXMl.

I would not expect false under either of these tests.

  $xml=new SimpleXMLElement('<a><b>123</b></a>');
  var_dump($xml);
  echo $xml ? "true": "false";

or

  $xml=new SimpleXMLElement('<a><b></b></a>');
  var_dump($xml);
  echo $xml ? "true": "false";

however the second returns false even though an XMLSimpleElement object is returned. I have the same issue with an xml doc with namespaces everywhere.

it means I cannot test for a failed XML parsing as if (!xml) returns false

but $xml->childen($namespace) does not.

Please advise TIA Ephraim


Solution

  • I can't reproduce your issue but I'll try to provide a couple of hints.

    First, here's the rule when converting objects to booleans:

    When converting to boolean, the following values are considered FALSE:
    [...] the special type NULL (including unset variables)
    [...] SimpleXML objects created from empty tags

    Every other value is considered TRUE (including any resource).

    Second, the SimpleXMLElement constructor always returns an object but it can throw a warning and an exception.

    So these are the possibilities:

    // Casts as TRUE because it's an object
    $xml=new SimpleXMLElement('<a><b>123</b></a>');
    var_dump($xml, (bool)$xml);
    unset($xml);
    
    // Casts as FALSE because it's an SimpleXMLElement object for an empty tag
    $xml=new SimpleXMLElement('<a />');
    var_dump($xml, (bool)$xml);
    unset($xml);
    
    // Casts as FALSE because the $xml variable was never set sucessfully so it's not even set
    try{
        $xml=new SimpleXMLElement('');
    }catch(Exception $e){
    }
    var_dump($xml, (bool)$xml); // Notice: Undefined variable: xml
    unset($xml);