php中simplexml_load_string使用实例分享
发布:smiling 来源: PHP粉丝网 添加日期:2020-09-14 14:49:01 浏览: 评论:0
这篇文章主要介绍了php中simplexml_load_string使用实例,需要的朋友可以参考下,先用一段代码重现一下问题,乍一看,结果很让人费解:
- $string = <<
- hello
- world
- EOF;
- $data = simplexml_load_string($string);
- print_r($data);
- print_r($data->foo);
乍一看,结果很让人费解:
- SimpleXMLElement Object
- (
- [foo] => Array
- (
- [0] => SimpleXMLElement Object
- (
- [bar] => hello
- )
- [1] => SimpleXMLElement Object
- (
- [bar] => world
- )
- )
- )
- SimpleXMLElement Object
- (
- [bar] => hello
- )
明明print_r显示foo是一个有两个bar元素的数组,但是最后却仅仅显示了一个bar元素!
原因其实很简单,在如上所示simplexml_load_string的结果里,foo并不是数组,而是一个迭代对象!
可以这样确认:
- foreach ($data->foo as $v) print_r($v);
- foreach ($data->children() as $v) print_r($v);
看来,print_r或者var_dump之类的表象并不完全可信,自己多留心吧。
假如我们获取的XML数据如下:(可以使用curl、fsockopen等方式获取),代码如下:
- 你好
- Array;Array;Array;
- Haven't seen you for a long time. How are you?
- 多日不见了,你好吗?
- Hello! How are you?
- 嘿,你好?
- Hello, Brooks!How are you?
- 喂,布鲁克斯!你好吗?
- Hi, Barbara, how are you?
- 嘿,芭芭拉,你好吗?
- How are you? -Quite well, thank you.
- 你好吗?-很好,谢谢你。
经过simplexml_load_string得到:
- SimpleXMLElement Object
- (
- [@attributes] => Array
- (
- [num] => 219
- [id] => 219
- [name] => 219
- )
- [key] => 你好
- [pos] => SimpleXMLElement Object
- (
- )
- [acceptation] => Array;Array;Array;
- [sent] => Array
- (
- [0] => SimpleXMLElement Object
- (
- [orig] => Haven't seen you for a long time. How are you?
- [trans] => 多日不见了,你好吗?
- )
- [1] => SimpleXMLElement Object
- (
- [orig] => Hello! How are you?
- [trans] => 嘿,你好?
- )
- [2] => SimpleXMLElement Object
- (
- [orig] => Hello, Brooks!How are you?
- [trans] => 喂,布鲁克斯!你好吗?
- )
- [3] => SimpleXMLElement Object
- (
- [orig] => Hi, Barbara, how are you?
- [trans] => 嘿,芭芭拉,你好吗?
- )
- [4] => SimpleXMLElement Object
- (
- [orig] => How are you? -Quite well, thank you.
- [trans] => 你好吗?-很好,谢谢你。
- )
- )
- )
我们在PHP语言中可以用以下方法取得我们想要的值:
- $data = <<
- 你好
- Array;Array;Array;
- Haven't seen you for a long time. How are you?
- 多日不见了,你好吗?
- Hello! How are you?
- 嘿,你好?
- Hello, Brooks!How are you?
- 喂,布鲁克斯!你好吗?
- Hi, Barbara, how are you?
- 嘿,芭芭拉,你好吗?
- How are you? -Quite well, thank you.
- 你好吗?-很好,谢谢你。
- XML;
- $xmldata = simplexml_load_string($data);
- header("Content-Type: text/html; charset=UTF-8");
- print_r($xmldata);
- echo "
- ".trim($xmldata->sent[0]->orig); //Haven't seen you for a long time. How are you?
- echo "
- ".trim($xmldata->key); //你好
- ?>
Tags: simplexml_load_string
- 上一篇:php的hash算法介绍
- 下一篇:使用php记录用户通过搜索引擎进网站的关键词
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)