Home  >  Article  >  Backend Development  >  A few things to note about SimpleXML_PHP Tutorial

A few things to note about SimpleXML_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:39:28738browse

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);

$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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/486307.htmlTechArticleSimpleXML 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 = s...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn