使用 PHP simpleXML 查找我知道名称但不知道它所在位置的节点 [英] Using PHP simpleXML to find a node I know the name of but not where it resides

查看:27
本文介绍了使用 PHP simpleXML 查找我知道名称但不知道它所在位置的节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我知道我要查找的节点的名称,我需要在 PHP 中查询一个 XML 字符串,但我可能不一定知道该节点的路径.

I need to query an XML string in PHP were I know the names of the nodes I am looking for but I might not necessarily know the path to the node.

我想我可以用 xpath 做到这一点,但我不知道如何设置相对路径来查看文档中的任何地方,有人能指出我正确的方向.

I think I can do this with xpath but I can't work out how to set up a relative path to look anywhere in the document, could someone point me in the right direction.

我目前正在尝试使用 simpleXML 来实现这一点,但如果有更好的方法,我很乐意听到.

I am currently trying to acheive this with simpleXML, but if there is a better way of doing this I would love to hear it.

推荐答案

不要使用正则表达式解析 XML!

Don't use regexes to parse XML!

xpath 中的 descendant(双斜线)运算符将搜索所有后代以查找匹配项.

The descendant (double-slash) operator in xpath will search all descendants for a match.

$matches = $simplexmlelementobject->xpath('//nameOfElement');

上面等价于DOM方法getElementsByTagName

如果您对元素所在的位置有一个大致的了解,您可以使用后代运算符在某个节点下方进行搜索:

If you have a general idea of where the element lives, you can use the descendant operator to search below a certain node:

$matches = $simplexmlelementobject->xpath('someparentelement[@conditionalattr=something]//nameOfDescendantElementYouWant');

如果您需要使用 DOMDocument 而不是 SimpleXML,如有必要,您可以使用 DOMXPath 对象发出 xpath 指令.(留给读者作为练习.)

If you need to use DOMDocument instead of SimpleXML, you can issue xpath instructions with the DOMXPath object if necessary. (Left as an exercise for the reader.)

这篇关于使用 PHP simpleXML 查找我知道名称但不知道它所在位置的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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