PHP xpath - find an element with a value, and also get elements before and after an element

Let's say that I have this XML:

<images> <photo> <thumbImg>images/thumbs/002.jpg</thumbImg> <filename>002</filename> </photo> <photo> <thumbImg>images/thumbs/008.jpg</thumbImg> <filename>008</filename> </photo> <photo> <thumbImg>images/thumbs/003.jpg</thumbImg> <filename>003</filename> </photo> <photo> <thumbImg>images/thumbs/006.jpg</thumbImg> <filename>006</filename> </photo> <photo> <thumbImg>images/thumbs/005.jpg</thumbImg> <filename>005</filename> </photo> </images> 

And I want to find the element with the file name 003, and then find elements 1 before and 1 after this element. That's all, so I can get the data for the previous / next functionality, and also show the selected image on the page. I thought this would do:

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

But this print_r is an empty array ... Is there an easy way with xpath to do this, maybe? I thought I could do this by simply looping and putting the previous / next elements in the temp array, then as soon as it finds, it will break the loop and return the temporary data, but I thought that xpath could do this a little more elegantly.

EDIT: enabled - here's a clearer answer for siblings:

 // for the one prior //photo[filename='$image_id']/preceding-sibling::photo[1] // for the one after //photo[filename='$image_id']/following-sibling::photo[1] 
+6
source share
1 answer

Use this:

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

Source: https://habr.com/ru/post/890059/


All Articles