SimpleXML provides a set of simple and fast XML operation methods, which greatly improves the efficiency of XML operations. But sometimes carelessness can cause a lot of trouble. Look at the following piece of code:
$xml = simplexml_load_string(
$title = $xml->title;
echo $title;
$xml->title = test;
echo $title;
Guess what the second output result will be? It is test, not title as imagined. Why is this happening? Here’s why:
echo gettype($xml->title) // object
echo get_class($xml->title); // SimpleXMLElement
See, $xml->title is an instance of the SimpleXMLElement class, not a string. So $title actually holds a reference to the SimpleXMLElement class, not a copy of the string. If you want to get a copy of the string, you can only perform type conversion:
$title = (string)$xml->title; // Get string
$xml->title = test;
echo $title; // Output title
SimpleXMLElement should implement an interface similar to __tostring() (if you are interested, you can take a look at the source code of PHP, in "ext/simplexml/"), so that it can be expressed in expressions such as echo. Similar to a string. So there is another place to pay attention to:
$_SESSION[test] = $xml->title; // Save a SimpleXMLElement variable to SESSION.
$_SESSION[test] = (string)$xml->title; // string
$_SESSION[test] = strval($xml->title); // This works too.