Home  >  Article  >  php教程  >  SimpleXML的一点注意事项

SimpleXML的一点注意事项

WBOY
WBOYOriginal
2016-06-13 10:38:16760browse

SimpleXML提供了一套简单快速的XML操作方法,大大地提高了XML操作的效率。但是有时不小心也会带来不小的麻烦,看下面一段代码:

$xml = simplexml_load_string(title);

$title = $xml->title;

echo $title;

$xml->title = test;

echo $title;
 


猜猜第二个输出结果会是多少?是test,而不是想像中的title。为什么会这样呢?原因在这里:

echo gettype($xml->title)  // object

echo get_class($xml->title);  // SimpleXMLElement
 


看到了吗,$xml->title是一个SimpleXMLElement类的实例,而不是字符串。所以$title实际上保存的是一个到SimpleXMLElement类的一个引用,而不是字符串的副本。想要得到字符串的副本只能进行类型转换:

$title = (string)$xml->title; // 获得字符串

$xml->title = test;

echo $title; // 输出title
 


SimpleXMLElement应该是实现了一个类似于__tostring()的接口(有兴趣的可以去看一下PHP的源码,在"ext/simplexml/"中),才能在echo等表达式中表现类似于一个字符串。所以还有个地方需要注意:

$_SESSION[test] = $xml->title; // 保存一个SimpleXMLElement变量到SESSION中。

$_SESSION[test] = (string)$xml->title; // 字符串

$_SESSION[test] = strval($xml->title); // 这样也行。
 

 

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
Previous article:php函数笔记Next article:SVN入门及配置使用