php loadxml 读取节点,PHP搜索并读取XML文件中节点数据

看似很简单的事情,却花了好几个小时,心塞。在下面的文件中,找一个 id=6 时的url。文件名叫my.xml。

0

http://www.000.com

1

http://www.1111.com

4

http://www.44444.com

6

http://www.66666.com

在Zend Framework的控制器某动作中完成那个操作。代码段如下:

$file = file_get_contents('my.xml');

$xml = simplexml_load_string($file);

$result = $xml->xpath('/urlfile/urls');

require_once('Zend/Debug.php');

Zend_Debug::Dump($result);

结果,在urls这个节点的层次上,变成了普通数组。其下一层,仍然是SimpleXMLElement对象。Dump出来的数据如下:

array(4) {

[0] => object(SimpleXMLElement)#41 (2) {

["id"] => string(1) "0"

["url"] => string(18) "http://www.000.com"

}

[1] => object(SimpleXMLElement)#42 (2) {

["id"] => string(1) "1"

["url"] => string(41) "http://www.1111.com"

}

[2] => object(SimpleXMLElement)#43 (2) {

["id"] => string(1) "4"

["url"] => string(33) "http://www.4444.com"

}

[3] => object(SimpleXMLElement)#44 (2) {

["id"] => string(1) "6"

["url"] => string(33) "http://www.6666.com"

}

}

有区别吗?有!要是当它是普通数组,你肯定会这样找那个id=6时对应的url。

foreach ($result as $k => $list )

{

if($list['id'] == $id )

{

$row['url'] = $list['url'];

//$row是我要送到页的一个数组,里面还有其它很多数据

}

}

结果你发现,

$row['url'] = null

正确的方法是:

foreach ($result as $k => $list )

{

if($list->id == $id )

{

$row['url'] = $list->url;

//$row是我要送到页的一个数组,里面还有其它很多数据

}

}

是$list->id而不是$list['id']。是$list->url,而不$list['url']。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值