PHP xpath() Function

Definition and Usage

The xpath() function runs an XPath query on the XML document.

If successful, returns an array containing a SimpleXMLElement object. If failed, returns false.

Syntax

class SimpleXMLElement
{
string xpath(path)
}
Parameters Description
path Required. XPath path.

Example

XML File:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP Code:

<?php
$xml = simplexml_load_file("test.xml");
$result = $xml->xpath("from");
print_r($result);
?>

Output:

Array
(
[0] => SimpleXMLElement Object
  (
  [0] => John
  )
)