xpath在php中的两个小疑点 请大家帮忙

php中文网
发布: 2016-06-13 13:24:02
原创
1233人浏览过

xpath在php中的两个小问题 请大家帮忙
例如一个xml文件如下:

 
 
 



 
 
 
 
如果我已知其中一个pet的type(small) color(white) 和age(5),想用xpath去得到那个pet的id 应该怎么弄?因为pet的下级都是并列的关系,再加上查完还得返回上一级(pet)那去得到id 我就不知道怎们弄了

第二个问题是在用xpath的过程中 我们会用到类似 /pet/type......... 如果在php中 我有一个变量 例如$str="type",那么在xpath中 可以写 /pet/$str............ 吗? 也就是说$str 里的值就相当于 type。 如果可以的话正确的完整的格式应该是怎么写?

------解决方案--------------------
第一个需要遍历。
第二个问题:可以,但是要这样写:$xml->xpath("/pet/$str");
------解决方案--------------------

PHP code
[User:root Time:00:07:19 Path:/home/liangdong/php]$ php xpath.php 
type:small
color:white
age:5
[User:root Time:00:07:19 Path:/home/liangdong/php]$ cat xpath.php 
<?php $str = <<<EOF
<?xml version="1.0" encoding="utf8" ?><pets><pet id="01"><type resource="big"></type><color resource="black"></color><age resource="2"></age></pet><pet id="02"><type resource="small"></type><color resource="white"></color><age resource="5"></age></pet></pets>
EOF;

$xml = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOBLANKS);
$res = $xml-&gt;xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");
foreach ($res as $node) { 
        $children = $node-&gt;children();
        foreach ($children as $child) {
                echo $child-&gt;getName() . ":" . $child['resource'] . PHP_EOL;
        }
}
?&gt;
<br><font color="#e78608">------解决方案--------------------</font><br>
登录后复制
PHP code
$str = 
<pets><pet id="01"><type resource="big"></type><color resource="black"></color><age resource="2"></age></pet><pet id="02"><type resource="small"></type><color resource="white"></color><age resource="5"></age></pet></pets>
EOF;

$xml = simplexml_load_string($str);
$res = $xml-&gt;xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");

echo $res[0]-&gt;attributes()-&gt;id; //02 <div class="clear"></div>
登录后复制
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号