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;