Using PHP simpleXML to find a node I know the name of but not where it resides

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.

Answers


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


Need Your Help

PHP: why i am getting this error ??? “syntax error, unexpected '{'”

php syntax if-statement

i wanted to arrange this arrays element in assending order and wrote the below code :

How to use spring-ws client to call the same webservice using different keystore

java spring ssl https spring-ws

I have some application that need to run in the same Application server. Each application need to authenticate through the same web service using a certificate specific for that application.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.