SimpleXML: Selecting Elements Which Have A Certain Attribute Value

dimo414 picture dimo414 · Jun 14, 2009 · Viewed 33.1k times · Source

In an XML document, I have elements which share the same name, but the value of an attribute defines what type of data it is, and I want to select all of those elements which have a certain value from the document. Do I need to use XPath (and if so, could you suggest the right syntax) or is there a more elegant solution?

Here's some example XML:

<object>
  <data type="me">myname</data>
  <data type="you">yourname</data>
  <data type="me">myothername</data>
</object>

And I want to select the contents of all <data> tags children of <object> who's type is me.

PS - I'm trying to interface with the Netflix API using PHP - this shouldn't matter for my question, but if you want to suggest a good/better way to do so, I'm all ears.

Answer

Gumbo picture Gumbo · Jun 14, 2009

Try this XPath:

/object/data[@type="me"]

Which reads as:

  • Select (/) children of the current element called object
  • Select (/) their children called data
  • Filter ([...]) that list to elements where ...
    • the attribute type (the @ means "attribute")
    • has the text value me

So:

$myDataObjects = $simplexml->xpath('/object/data[@type="me"]');

If object is not the root of your document, you might want to use //object/data[@type="me"] instead. The // means "find all descendents" rather than "find all children".