0

Possible Duplicate:
A simple program to CRUD node and node values of xml file

How would I get a specific Attribute out of this XML feed?

Example - I have been using a line similar to this to get other XML details but I am unsure how I could change it to get a specific Attribute.

$mainPropertyDetails = $mainPropertyUrl->Attributes->attribute;

Attributes:

<Attributes>
<Attribute>
<Name>bedrooms</Name>
<DisplayName>Bedrooms</DisplayName>
<Value>4 bedrooms</Value>
</Attribute>
<Attribute>
<Name>bathrooms</Name>
<DisplayName>Bathrooms</DisplayName>
<Value>2 bathrooms</Value>
</Attribute>
<Attribute>
<Name>property_type</Name>
<DisplayName>Property type</DisplayName>
<Value>House</Value>
</Attribute>
Community
  • 1
  • 1
Jess McKenzie
  • 8,345
  • 27
  • 100
  • 170
  • 1
    Use `$sxe = new SimpleXMLElement($xml); var_dump($sxe->Attribute[0]);` Where `0` is the specific ID of the attribute you want – Baba Oct 29 '12 at 00:44

1 Answers1

1

SimpleXML implements these nodes as an array. If you were to var_dump() this, you would see something like:

// Dump the whole Attributes array
php > var_dump($xml->Attributes);

object(SimpleXMLElement)#6 (1) {
  ["Attribute"]=>
  array(3) {
    [0]=>
    object(SimpleXMLElement)#2 (3) {
      ["Name"]=>
      string(8) "bedrooms"
      ["DisplayName"]=>
      string(8) "Bedrooms"
      ["Value"]=>
      string(10) "4 bedrooms"
    }
    [1]=>
    object(SimpleXMLElement)#5 (3) {
      ["Name"]=>
      string(9) "bathrooms"
      ["DisplayName"]=>
      string(9) "Bathrooms"
      ["Value"]=>
      string(11) "2 bathrooms"
    }
    [2]=>
    object(SimpleXMLElement)#3 (3) {
      ["Name"]=>
      string(13) "property_type"
      ["DisplayName"]=>
      string(13) "Property type"
      ["Value"]=>
      string(5) "House"
    }
  }
}

It is therefore just a matter of accessing specific ones by their array index:

// Get the second Attribute node
var_dump($xml->Attributes[0]->Attribute[1]);

object(SimpleXMLElement)#6 (3) {
  ["Name"]=>
  string(9) "bathrooms"
  ["DisplayName"]=>
  string(9) "Bathrooms"
  ["Value"]=>
  string(11) "2 bathrooms"
}

Get the Attribute node based on a child's value:

Using xpath() you can query for the parent Attribute node based on a child's text value:

// Get the Attribute containing the Bathrooms DisplayName
// Child's text value is queried via [AttrName/text()="value"]
var_dump($xml->xpath('//Attributes/Attribute[DisplayName/text()="Bathrooms"]');

array(1) {
  [0]=>
  object(SimpleXMLElement)#6 (3) {
    ["Name"]=>
    string(9) "bathrooms"
    ["DisplayName"]=>
    string(9) "Bathrooms"
    ["Value"]=>
    string(11) "2 bathrooms"
  }
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390