XPath two small doubts in PHP please help us

Source: Internet
Author: User
Tags xpath
XPath in PHP two small problems please help us
For example, an XML file looks like this:











What if I knew that one of the pet's type (small) color (white) and age (5) would want to use XPath to get the ID of that pet? Because pet subordinates are tied to the relationship, plus to go back to the previous level (PET) to get the ID I don't know how to get

The second problem is that in the process of using XPath we will use similar/pet/type ... If I have a variable such as $str= "type" in PHP, then you can write/pet/$str in XPath ... It? This means that the value in $str is equivalent to type. If so, what should be the correct complete format to write?

------Solution--------------------
The first one needs to traverse.
Second question: Yes, but write this: $xml->xpath ("/pet/$str");
------Solution--------------------
PHP Code
[User:root time:00:07:19 path:/home/liangdong/php]$ php xpath.php type:smallcolor:whiteage:5[user:root Time:00:07:19 path:/home/liangdong/php]$ Cat xpath.php
  
  
   
    
     
      
        
       
      
       
    
    
 
    
    
     
    
 
  

   
  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 = $no        De->children (); foreach ($children as $child) {echo $child->getname (). ":" . $child [' Resource '].        Php_eol; }}?>
------Solution--------------------
PHP code
 $str = << 
      
       
        
         
         
        
       
         resource= "small"/> 
         
        
       EOF; $xml = Simplexml_loa D_string ($STR); $res = $xml->xpath ("/pets/pet[type[@resource = ' small ') and color[@resource = ' white '] and age[@ Resource= ' 5 ']]; echo $res [0]->attributes ()->id; 
      
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.