>  기사  >  백엔드 개발  >  xpath在php中的两个小疑点 请大家帮忙

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

WBOY
WBOY원래의
2016-06-13 13:24:02887검색

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->xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");
foreach ($res as $node) { 
        $children = $node->children();
        foreach ($children as $child) {
                echo $child->getName() . ":" . $child['resource'] . PHP_EOL;
        }
}
?>
<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->xpath("/pets/pet[type[@resource='small'] and color[@resource='white'] and age[@resource='5']]");

echo $res[0]->attributes()->id; //02 <div class="clear">
                 
              
              
        
            </div>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.