Successfully parsed SimpleXMLElement against false, returning true

I had a very inconvenient and specific problem with evaluating simplexml.

The code:

$simplexml = simplexml_load_string($xmlstring);
var_dump($simplexml);
var_dump($simplexml == false); //this comparison

var_dump ($ simplexml) returns the actual structure of my simplexml, but the comparison returns "true" for this particular simplexml, which I cannot show the structure due to my contract.
I am sure there is a very specific problem because I tried other XML lines and the comparison returns false.

$simplexml = simplexml_load_string('<a><b>test</b></a>');
var_dump($simplexml); //returns the actual structure
var_dump($simplexml == false); //returns false

I solved the problem using the '===' operator, but I am not satisfied that it works. I want to understand why the '==' operator returns true.
I read about two operators and SimpleXMLElement, and in my opinion, it should return false for both operators. What are the possible reasons for comparing the successfully processed SimpleXMLElement and the boolean "false" to return "true"?

+3
source share
3 answers

Take a look here: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

It says that SimpleXML objects created from empty tags are evaluated as false. Maybe what's going on?

+1
source

boolean casting (bool)

$simplexml = simplexml_load_string('<a><b>test</b></a>');
var_dump($simplexml); //returns the actual structure
var_dump((bool) $simplexml); // Retuns true
var_dump((bool) $simplexml == false); //returns false
var_dump((bool) $simplexml === false); //returns false   

: http://codepad.viper-7.com/xZtuNG

=== ... , === true, ! == ( ), , === .

1

. - https://bugs.php.net/bug.php?id=54547

+2
var_dump($simplexml == false); //returns false

This is expected behavior, and this is due to comparing data by “parsing” the data. In PHP, NULL, zero, and boolean FALSE are considered "Falsy"; everything else is considered "true." Inside parentheses, PHP evaluates the expression. In this case, PHP evaluates the comparison of the named variable OBJECT and logical FALSE. They do not match, so the return value from the comparison is FALSE and this is what * var_dump () * prints.

You can take advantage of this in the if () statement. Example:

$simplexml = SimpleXML_Load_String('<a><b>test</b></a>');
if ($simplexml) { /* process the object */ }
else { /* process the failure to load the XML */ }
+2
source

All Articles