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

17,649

Solution 1

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

Solution 2

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

Share:
17,649
Toby
Author by

Toby

I am a developer who focuses mainly on web technologies. I also run a handful of websites covering a wide range of topics. One of my favourites because it annoys so many people is howoldistheinter.net where I make the distinction between www and the internet. My company specialise in Ruby development, you can hire us for a Ruby project if you like. On my site I write Ruby articles amongst other posts.

Updated on June 14, 2022

Comments

  • Toby
    Toby almost 2 years

    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.

  • Toby
    Toby over 12 years
    Unfortunately there isn't a specific example, the XML could change but the node name will remain constant, which is why I am looking for a general solution. Thanks for the link, I will read it now.
  • goat
    goat over 12 years
    This works. Also, see SimpleXMLElement::registerXPathNamespace if the xml element name is namespaced eg <Name:Toby>