Example 1 — Select Elements by Path
Load a small library and select every title with a simple path.
<?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
- The XML is joined from short pieces so the example stays easy to read, and it holds three book elements.
- xpath('/library/book/title') starts at the root and picks every title inside every book.
- The method returns an array, and count() shows that it holds 3 matches.
- foreach prints each match, and echo turns each element into its text.

