Blog : SimpleXMLElement::attributes

SimpleXMLElement::attributes

(PHP 5 >= 5.0.1)

SimpleXMLElement::attributes — Identifie les attributs d'un élément

Description

public SimpleXMLElement SimpleXMLElement::attributes ([ string $ns = NULL [, bool $is_prefix = false ]] )

Fournit les attributs et les valeurs définies dans une balise XML.

Note: SimpleXML ajoute des propriétés itératives pour presque toutes ses méthodes. Celles-ci ne peuvent être vues en utilisant var_dump() ou tout autre fonction qui examine les objets.

Exemples

Exemple #1 Interprétation d'une chaîne XML
$string = <<
 1
XML;$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
 echo $a,'="',$b,"\"\n";
}?>

L'exemple ci-dessus va afficher :

name="one"
game="lonely"

User Contributed Notes 13 notes

Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condição definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)



 
  PHP
  www.php.net
 
 
  Java
  www.oracle.com/br/technologies/java/‎
 


Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.


$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {
 
  $role = $child->attributes();

  foreach($child as $key => $value) {
   
  if($role == "Language")
  echo("[".$key ."] ".$value . "
");
   
  }
}?>
output:
saída:

[name] PHP
[link] www.php.net

Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

$xml = <<
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 
 

XML;$sxml = new SimpleXMLElement($xml);/**
 * Access attribute of default namespace
 */var_dump((string) $sxml->Table[0]['Foo']);// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);// outputs: 0var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);// outputs: '7'?>

It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

SimpleXMLElement Object(
  [@attributes] => Array
  (
  [id] => 55555
  )

  [text] => "hello world")?>
Then using a function

function xml_attribute($object, $attribute)
{
  if(isset($object[$attribute]))
  return (string) $object[$attribute];
}?>
I can get the "id" like this

print xml_attribute($xml, 'id'); //prints "55555"?>

$att = 'attribueName';// You can access an element's attribute just like this :$attribute = $element->attributes()->$att;// This will save the value of the attribute, and not the objet$attribute = (string)$element->attributes()->$att;// You also can edit it this way :$element->attributes()->$att = 'New value of the attribute';?>

Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

//- $node is a SimpleXMLElement object$atts_object = $node->attributes(); //- get all attributes, this is not a real array$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after$atts_array = $atts_array['@attributes'];var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
  //-  public '@attributes' => ...var_dump($atts_array); //- outputs array (size=11) ...?>Hope this helps!

If you want to save the value of an attribute into an array, typecast it to a string.

// stores an xml-element-object $dataStore['value'] = $attributes->myValue // stores the value of the attribute $dataStore['value'] = (string)$attributes->myValue
?>

in order to get a possibly present xml:space attribute, use the following construct:

$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;?>
This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.

Reading the attributes of the root element with name space prefixes as in an Atom feed



$xml =  @simplexml_load_file($feed); $att_gd = $xml->attributes("gd",1);$Etag = $att_gd["etag"];?>

To get an attribute in the node, use node->attributes()->attributeName

You can also access the node as an array to get attributes:


$xml = simplexml_load_file('file.xml');

echo 'Attribute: ' . $xml['attribute']; ?>

here's a simple function to get an attribute by name, based on the example

function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
  if ($a == $attribute) {
  $return = $b;
  }
  }
  if($return) {
  return $return;
  }
} ?>

How I will use this for an External XML file..?

$xml = <<
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 
 

XML;$sxml = new SimpleXMLElement($xml);/**
 * Access attribute of default namespace
 */var_dump((string) $sxml->Table[0]['Foo']);// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);// outputs: 0var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);// outputs: '7'?>

So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:


 
  Navarro Corp.
 
 
  Performant Systems
 
 
  Digital Showcase
 


Example of listing both the ID Attribute and Company Element values:
 
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
  $arr = $node->attributes();  // returns an array
  print ("ID=".$arr["ID"]);  // get the value of this attribute
  print ("  Company=".$node->Company);
  print ("

");
}?>