php xml对象比较

I get data from an XML object in PHP and use the "==" operator, but we do not get equality. It seems like a very basic question, but I cannot find it anywhere.

Minimal example:

<?php
// Load the file
$xmlData = "<?xml version='1.0' encoding='UTF-8' ?>
<root>
<a>animalia</a>
<b>arthropoda
<parent>animalia</parent>
</b>
</root>";

$xml=simplexml_load_string($xmlData) or die("Error: Cannot create object");
print_r($xml);

//Extract the data

$x=$xml->a;
$y=$xml->b->parent;

// Test whether they are equal

if ($x==$y) {
  echo $x." = ".$y;
}
else {
  echo "'".$x."' does not equal '".$y."'";
}
?>

This gives me the result: 'animalia' does not equal 'animalia'

Note, if I write either

print_r($x); 

or

print_r($x);

I get the output: SimpleXMLElement Object ( [0] => animalia )

So the question is, why these are not considered equal? Thanks in advance.

trim — Strip whitespace (or other characters) from the beginning and end of a string

<?php
// Load the file
$xmlData = "<?xml version='1.0' encoding='UTF-8' ?>
<root>
<a>animalia</a>
<b>arthropoda
<parent>animalia</parent>
</b>
</root>";

$xml=simplexml_load_string($xmlData) or die("Error: Cannot create object");
print_r($xml);

//Extract the data
$x=$xml->a;
$y=$xml->b->parent;
// Test whether they are equal
if (trim($x)==trim($y)) {
  echo $x." = ".$y;
}
else {
  echo "'".$x."' does not equal '".$y."'";
}
?>

Output:

animalia = animalia

Read About XML Whitespaces

You are not comparing two strings, you are comparing two different nodes ( <a>animalia</a> vs <parent>animalia</parent> ).

They are two different SimpleXML objects.

To compare node values, cast objects as string:

if( (string) $x == (string) $y )

or:

if( $x->__toString() == $y->__toString() )