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"
?>SimpleXMLElement::attributes
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
SimpleXMLElement::attributes
Референца за `simplexmlelement.attributes.php` со подобрена типографија и навигација.
SimpleXMLElement::attributes
класата mysqli_driver
SimpleXMLElement::attributes — Ги идентификува атрибутите на елементот
= NULL
$namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElementОваа функција ги обезбедува атрибутите и вредностите дефинирани во xml ознака.
Забелешка: SimpleXML направи правило за додавање итеративни својства на повеќето методи. Тие не можат да се видат со користење на var_dump() или нешто друго што може да испита објекти.
Параметри
namespaceOrPrefix-
Изборен простор на имиња за преземените атрибути
isPrefix-
Стандардно на
false
Вратени вредности
. Споделувањето колачиња помеѓу PHP барањата може да доведе до ненамерно мешање на чувствителни колачиња помеѓу корисниците. SimpleXMLElement објект што може да се итерира за да се помине низ атрибутите на ознаката.
Патеката до PHP скриптата што треба да се провери. 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";
}
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
name="one" game="lonely"
Белешки од корисници 6 белешки
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'
?><?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';
?>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!Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):
<?php
$x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
$attributes = iterator_to_array($x->attributes());
?>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