PHP SimpleXMLElement::xpath() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
SimpleXML

Definition

In PHP, SimpleXMLElement::xpath() runs an XPath query on an XML element and returns the matching elements or attributes as an array.

XPath is a small query language for XML. It lets you pick elements by path, such as /library/book/title, or by a condition, such as //book[@year='2024']. The method always returns an array, so use foreach to read the matches, or index [0] to read the first one.

Syntax

Call SimpleXMLElement::xpath() with the values you need. Start with this line.

PHP
$titles = $xml->xpath('/library/book/title');
CallWhat it does
$xml->xpath('/library/book/title')Returns every title element that sits inside a book inside the library root.
$xml->xpath("//book[@year='2024']/title")Returns the titles of books whose year attribute is 2024.
$xml->xpath('/library/book/@id')Returns the id attribute of every book.

A path that starts with / begins at the document root. A path that starts with // searches the whole document. A query with no matches returns an empty array, not false. Each result is a SimpleXMLElement, so cast it with (string) when you need text.

Library declarations
PHP
SimpleXMLElement::xpath(string $expression): array|false|null

Parameters

ParameterDescription
expressionRequired. The XPath expression to run, for example /library/book/title or //book[@id='b2'].

Return Value

Return ValueDescription
arrayAn array of SimpleXMLElement objects for every match. The array is empty when nothing matches.
falseReturned, with a warning, when the expression is not valid XPath. The signature also allows null in rare error cases.

PHP Examples

Example 1 — Select Elements by Path

Load a small library and select every title with a simple path.

PHP
<?php
$xml = simplexml_load_string(
    '<library>'
    . '<book id="b1" year="2023"><title>PHP Basics</title><price>9</price></book>'
    . '<book id="b2" year="2024"><title>Learn XML</title><price>15</price></book>'
    . '<book id="b3" year="2024"><title>Web Tips</title><price>12</price></book>'
    . '</library>'
);

$titles = $xml->xpath('/library/book/title');

echo 'Found: ', count($titles), PHP_EOL;
foreach ($titles as $title) {
    echo $title, PHP_EOL;
}

How It Works

  1. The XML is joined from short pieces so the example stays easy to read, and it holds three book elements.
  2. xpath('/library/book/title') starts at the root and picks every title inside every book.
  3. The method returns an array, and count() shows that it holds 3 matches.
  4. foreach prints each match, and echo turns each element into its text.

Example 2 — Filter with Conditions

Use a condition in square brackets to keep only some elements. A query with no match returns an empty array.

PHP
<?php
$xml = simplexml_load_string(
    '<library>'
    . '<book id="b1" year="2023"><title>PHP Basics</title><price>9</price></book>'
    . '<book id="b2" year="2024"><title>Learn XML</title><price>15</price></book>'
    . '<book id="b3" year="2024"><title>Web Tips</title><price>12</price></book>'
    . '</library>'
);

foreach ($xml->xpath("//book[@year='2024']/title") as $title) {
    echo '2024: ', $title, PHP_EOL;
}

foreach ($xml->xpath('//book[price>10]/title') as $title) {
    echo 'Over 10: ', $title, PHP_EOL;
}

$none = $xml->xpath("//book[@year='2030']/title");
echo 'No match: ', var_export($none, true), PHP_EOL;

How It Works

  1. [@year='2024'] keeps only books whose year attribute equals 2024, and /title then picks their titles.
  2. [price>10] compares the price child as a number, so only the books with price 15 and 12 stay.
  3. A query with no matching book does not fail. It returns an empty array.
  4. var_export() prints the empty array over two lines, which makes it clear that nothing was found.

Example 3 — Read Attributes and the First Match

XPath can select attributes too. Use index [0] to read only the first match.

PHP
<?php
$xml = simplexml_load_string(
    '<library>'
    . '<book id="b1" year="2023"><title>PHP Basics</title></book>'
    . '<book id="b2" year="2024"><title>Learn XML</title></book>'
    . '<book id="b3" year="2024"><title>Web Tips</title></book>'
    . '</library>'
);

$ids = [];
foreach ($xml->xpath('/library/book/@id') as $id) {
    $ids[] = (string) $id;
}
echo 'Ids: ', implode(', ', $ids), PHP_EOL;

$result = $xml->xpath('//book[@id="b2"]/title');
if (isset($result[0])) {
    echo 'Book b2: ', $result[0], PHP_EOL;
}

How It Works

  1. /library/book/@id selects the id attribute of each book, and each match is a SimpleXMLElement.
  2. (string) turns each attribute into plain text, and implode() joins the three ids.
  3. //book[@id="b2"]/title searches the whole document for the book with id b2 and picks its title.
  4. isset($result[0]) checks that there is a first match before echo prints it.

Frequently Asked Questions

It runs an XPath query on an element and returns the matches as an array of SimpleXMLElement objects. You can select elements, attributes, or elements that meet a condition.
It returns an empty array, not false. That is why a foreach over the result is safe even when there is no match.
A single / follows an exact path from the start, such as /library/book. A double // searches the whole document, such as //book, no matter where the book element sits.
Read index 0 of the result, for example $result[0]. Use isset($result[0]) first so you do not read a position that does not exist.
Yes. When you call it on a child, a path that starts with / still begins at the document root. A relative path such as title starts from that child element.

Next: SimpleXMLElement::current()

SimpleXMLElement::current() returns the child element that the iterator points to right no.

SimpleXMLElement::current() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful