Using PHP simpleXML to find a node I know the name

2019-04-02 07:40发布

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.

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.

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.

3条回答
Animai°情兽
2楼-- · 2019-04-02 08:16

While I think using simplexml's xpath is really easy and effective for this, in case you have more to do, you might find some of these alternatives more familiar to you, as they use the dom, or css selectors instead of xpath.

http://code.google.com/p/phpquery/

http://querypath.org/

http://www.php.net/manual/en/domelement.getelementsbytagname.php

查看更多
等我变得足够好
3楼-- · 2019-04-02 08:21

Don't use regexes to parse XML!

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

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

The above is equivalent to the DOM method 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');

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.)

查看更多
来,给爷笑一个
4楼-- · 2019-04-02 08:26

i am not sure exactly what the XML structure looks like but i've used this blog post to help out with some issues i've run into with XML parsing. it appears to explain the basics, plus always refer to php.net

i hope this helps, but without seeing the full issue, i can't fully answer the question.

查看更多
登录 后发表回答