PHP SimpleXMLElement - xpath() Method
The PHP SimpleXMLElement::xpath() method searches the SimpleXML node for children matching the XPath expression.
Syntax
public SimpleXMLElement::xpath(expression)
Parameters
expression |
Required. Specify an XPath path. |
Return Value
Returns an array of SimpleXMLElement objects on success, or null or false in case of an error.
Example: xpath() example
The example below shows the usage of SimpleXMLElement::xpath() method.
<?php $xmlstr = <<<XML <userlist> <user id="John123"> <name>John Smith</name> <city>New York</city> <phone>+1-8054098000</phone> </user> <user id="Marry2015"> <name>Marry G.</name> <city>London</city> <phone>+33-147996101</phone> </user> </userlist> XML; $xml = new SimpleXMLElement($xmlstr); //search for <userlist><user><name> $result = $xml->xpath('/userlist/user/name'); foreach($result as $node){ echo "/userlist/user/name: $node \n"; } //relative paths also work $result = $xml->xpath('user/name'); foreach($result as $node){ echo "user/name: $node \n"; } ?>
The output of the above code will be:
/userlist/user/name: John Smith /userlist/user/name: Marry G. user/name: John Smith user/name: Marry G.
❮ PHP SimpleXML Reference