dimo414 dimo414 - 3 years ago 164
PHP Question

SimpleXML: Selecting Elements Which Have A Certain Attribute Value

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:

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

And I want to select the contents of all
tags children of
who's type is

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 Source

Try this XPath:



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

And if object is not the root of your document, use //object/data[@type="me"] instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download