SimpleXMLElement::attributes

(PHP 5 >= 5.0.1)

SimpleXMLElement::attributesВозвращает атрибуты элемента

Описание

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

Эта функция возвращает названия и значения атрибутов установленные в xml теге.

Замечание: SimpleXML содержит правило добавления итеративных свойств к большинству методов. Они не могут быть просмотрены с использованием var_dump() или каких-либо других средств анализа объектов.

Список параметров

ns

Не обязательное пространство имен для извлеченных атрибутов

is_prefix

По умолчанию FALSE

Возвращаемые значения

Возвращает итеративный объект SimpleXMLElement, по которому можно перемещаться для перебора всех атрибутов тега.

Вернет NULL если вызванный объект SimpleXMLElement уже представляет собой атрибуты, а не тег.

Примеры

Пример #1 Интерпретация XML строки

<?php
$string 
= <<<XML
<a>
 <foo name="one" game="lonely">1</foo>
</a>
XML;

$xml simplexml_load_string($string);
foreach(
$xml->foo[0]->attributes() as $a => $b) {
    echo 
$a,'="',$b,"\"\n";
}
?>

Результат выполнения данного примера:

name="one"
game="lonely"

Коментарии

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

<?php
function findAttribute($object$attribute) {
  foreach(
$object->attributes() as $a => $b) {
    if (
$a == $attribute) {
     
$return $b;
    }
  } 
  if(
$return) {
    return 
$return;
  }
}
?>
2004-05-26 13:53:58
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
You can also access the node as an array to get attributes:

<?php

$xml 
simplexml_load_file('file.xml');

echo 
'Attribute: ' $xml['attribute'];

?>
2004-12-10 00:55:27
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
To get an attribute in the node, use node->attributes()->attributeName
2009-11-04 16:21:23
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Автор:
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.

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

    [
text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object$attribute)
{
    if(isset(
$object[$attribute]))
        return (string) 
$object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml'id'); //prints "55555"
?>
2010-04-10 22:46:05
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
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:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:
 
<?php
$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 (
"<p><hr>");
}
?>
2010-05-24 01:26:44
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Автор:
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
2011-04-02 12:07:16
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Автор:
<?php
$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';
?>
2011-04-27 16:12:39
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Автор:
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml 
=  @simplexml_load_file($feed); 
$att_gd $xml->attributes("gd",1);
$Etag $att_gd["etag"];
?>
2011-05-16 19:46:24
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml 
= <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
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: 0

var_dump((int) $sxml->Table[0]->attributes('ss'TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
2012-03-23 12:16:05
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $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!
2012-11-08 19:21:14
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$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.
2013-06-14 13:15:17
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
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)

<?xml version="1.0" encoding="UTF-8"?>

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/‎</link>
    </item>
</list>

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.

<?php

$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 "<br />");
           
        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
2013-09-07 08:11:24
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Автор:
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
2014-12-19 01:01:54
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see function.iterator-to-array):

<?php
      $x 
= new SimpleXMLElement('<div class="myclass" id="myid"/>');
     
$attributes iterator_to_array($x->attributes());
?>
2015-08-14 13:00:35
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes 
(but not both) without type-casting is to use the function `current()`:

<?php
$xml 
= new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
   
'bar' => [
       
$xml->bar,
       
current($xml->bar),
    ],
   
'baz' => [
       
$xml->baz->attributes(),
       
current($xml->baz->attributes()),
    ],
   
'qux' => [
       
// won't work here correctly
       
$xml->qux,
       
current($xml->qux),
       
$xml->qux->attributes(),
       
current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
2018-05-23 15:38:26
http://php5.kiev.ua/manual/ru/simplexmlelement.attributes.html

    Поддержать сайт на родительском проекте КГБ