PHP xpath-查找具有值的元素,并获取元素之前和之后的元素 [英] PHP xpath - find element with a value and also get elements before and after element

查看:81
本文介绍了PHP xpath-查找具有值的元素,并获取元素之前和之后的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有这个XML:

Lets say 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>

我想找到文件名值为003的元素,然后找到该元素之前1和之后1的元素.这就是全部,这样我就可以获取上一个/下一个功能的数据以及在页面上显示所选的图像.我当时想这样做:

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']");

但是print_r是一个空数组... xpath是否有一种简单的方法可以做到这一点?我认为我可以通过循环遍历并将prev/next元素放入temp数组中来做到这一点,然后一旦找到它,就可以中断循环并返回temp数据,但是我认为xpath也许可以做得更多优雅地.

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.

已解决-这是兄弟节点的更清晰答案:

solved - here's the clearer answer for the sibling nodes:

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

推荐答案

使用此:

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

这篇关于PHP xpath-查找具有值的元素,并获取元素之前和之后的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆