PHP Function Reference

PHP SimpleXMLElement - attributes() Method



The PHP SimpleXMLElement::attributes() method provides the attributes and values defined within an xml tag.

Syntax

public SimpleXMLElement::attributes(namespaceOrPrefix, isPrefix)

Parameters

namespaceOrPrefix Optional. Specify namespace for the retrieved attributes.
isPrefix Optional. Default is false.

Return Value

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns null if called on a SimpleXMLElement object that already represents an attribute and not a tag.

Example:

The example below shows the usage of SimpleXMLElement::attributes() method.

<?php
$xmlstr = <<<XML
<userlist> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
    <phone>+1-8054098000</phone>
  </user>
  
  <user id="Marry2015" game="group">
    <name>Marry G.</name>
    <city>London</city>
    <phone>+33-147996101</phone>
  </user> 
</userlist> 
XML;

$xml = simplexml_load_string($xmlstr);

foreach ($xml as $user) {
  foreach($user->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
  }
}
?>

The output of the above code will be:

id="John123"
game="lonely"
id="Marry2015"
game="group"

❮ PHP SimpleXML Reference