1

I have a xml-object looks like this:

<search typ="car" sub="all" out="test" epc="2" tsc="1" rcc="111" tpc="111" cur="DOL" itc="10">

Or with var_dump():

object(SimpleXMLElement)[1012]
  public 'search' => 
    object(SimpleXMLElement)[1078]
          public '@attributes' => 
            array (size=9)
              'typ' => string 'car' (length=8)
              'sub' => string 'all' (length=3)
              'out' => string 'test' (length=11)
              'epc' => string '2' (length=1)
              'tsc' => string '1' (length=1)
              'rcc' => string '111' (length=3)
              'tpc' => string '111' (length=3)
              'cur' => string 'DOL' (length=3)
              'itc' => string '10' (length=2)

How do I get access to the attributes of the xml knot?

Clément Malet
  • 5,062
  • 3
  • 29
  • 48
Zwen2012
  • 3,360
  • 9
  • 40
  • 67

2 Answers2

1

Just use ->attributes to access the node's attributes. Example:

$xml = simplexml_load_string($xml_string); // or load_file

echo '<pre>';
print_r($xml->attributes());

Individually:

// PHP 5.4 or greater (dereference)
echo $xml->attributes()['typ'];
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • Do you know something about the JMS Serializer? How can I get the attributes with the JMS? – Zwen2012 Aug 27 '14 at 14:22
  • Actually, most of the time, you don't need the `->attributes()` method at all. Nor do you need the array dereference if you are using it, because `->attributes()->typ` will then work. See my answer for a few examples of when you want this. – IMSoP Aug 27 '14 at 15:05
1

As shown on the basic usage examples in the manual, the standard way to access an attribute is using array access ($element['attributeName']), e.g.

echo $search['typ'];
$typ = (string)$search['typ'];

Note that the attribute is returned as an object, so you usually want to "cast" to string (or int, etc) when storing it in a variable.

To iterate over all attributes, you can use the ->attributes() method, e.g.

foreach ( $search->attributes() as $name => $value ) {
     echo "$name: $value\n";
     $some_hash[ $name ] = (string)$value;
}

The attributes() method is also needed if you have XML namespaces, e.g. `

$sx = simplexml_load_string(
    '<foo xlmns:bar="http://example.com#SOME_XMLNS" bar:becue="yum" />'
);
echo $sx->attributes('http://example.com#SOME_XMLNS')->becue;
// Or, shorter but will break if the XML is generated with different prefixes
echo $sx->attributes('bar', true)->becue;
IMSoP
  • 89,526
  • 13
  • 117
  • 169