PHP xpath – find element with a value and also get elements before and after element

Lets say I have this XML:


And I want to find the element with the filename value of 003 and then find the elements 1 prior and 1 after that element. This is all so I can get the data for a prev/next functionality as well as show the selected image on a page. I was thinking this would do it:

$image_id = "003";
$project = $xml_object->xpath("photo[filename='$image_id']");

But it print_r’s an empty array… Is there an easy way with xpath to do this perhaps? I figured that I could do it by just looping through and putting the prev/next elements into a temp array, then once it’s found, break the loop and return the temp data, but I thought xpath might be able to do it a little more elegantly.

EDIT: solved – here’s the clearer answer for the sibling nodes:

// for the one prior
// for the one after

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use this:

$project = $xml_object->xpath("//photo[filename='$image_id']");

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply