SimpleXML: Selecting Elements Which Have A Certain Attribute Value SimpleXML: Selecting Elements Which Have A Certain Attribute Value php php

SimpleXML: Selecting Elements Which Have A Certain Attribute Value


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


I just made a function to do this for me; it only grabs the first result though. Your mileage may vary.

function query_attribute($xmlNode, $attr_name, $attr_value) {  foreach($xmlNode as $node) {     if($node[$attr_name] == $attr_value) {        return $node;    }  }}

Usage:

echo query_attribute($MySimpleXmlNode->Customer, "type", "human")->Name;

(For the XML below)

<Root><Customer type="human"><Name>Sam Jones</name></Customer></Root>