PHP 8.4.1 Released!

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addAttribute Adiciona um atributo a elemento SimpleXML

Descrição

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Adiciona um atributo à elemento SimpleXML

Parâmetros

qualifiedName

O nome do atributo a ser adicionado.

value

O valor do atributo.

namespace

Se especificado, diz a qual namespace o atributo pertence.

Valor Retornado

Nenhum valor é retornado.

Exemplos

Nota:

Os exemplos listados podem incluir o arquivo exemplo.php, que referem-se a uma string XML encontrada no primeiro exemplo do guia de uso básico.

Exemplo #1 Adiciona atributos e filhos à um elemento SimpleXML

<?php

include 'exemplo.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('tipo', 'documentário');

$filme = $sxe->addChild('filme');
$filme->addChild('titulo', 'PHP2: Mais Estórias de Interpretadores');
$filme->addChild('resumo', 'É tudo é sobre as pessoas que fazem isso funcionar.');

$personagens = $filme->addChild('personagens');
$personagem = $personagens->addChild('personagem');
$personagem->addChild('nome', 'Sr. Interpretador');
$personagem->addChild('ator', 'Fulano de Tal');

$rating = $filme->addChild('classificacao', '5');
$rating->addAttribute('tipo', 'estrelas');

echo
$sxe->asXML();

?>

O exemplo acima produzirá algo semelhante a:

<?xml version="1.0" standalone="yes"?>
<filmes tipo="documentário">
 <filme>
  <titulo>PHP: Nos Bastidores do Interpretador</titulo>
  <personagens>
   <personagem>
    <nome>Srta. Codificadora</nome>
    <ator>Onlivia Actora</ator>
   </personagem>
   <personagem>
    <nome>Sr. Codificador</nome>
    <ator>El Act&#xF3;r</ator>
   </personagem>
  </personagens>
  <resumo>
   Então, essa linguagem. Se parece com uma linguagem de programação. Ou seria uma
   liguagem de scripts? Tudo é revelado nesta emocionante paródia de terror
   de um documentário.
  </resumo>
  <melhores-frases>
   <frase>O PHP resolve todos os meus problemas!</frase>
  </melhores-frases>
  <classificacao tipo="gostei">7</classificacao>
  <classificacao tipo="estrelas">5</classificacao>
 </filme>
 <filme>
  <titulo>PHP2: Mais Estórias de Interpretadores</titulo>
  <resumo>É tudo é sobre as pessoas que fazem isso funcionar.</resumo>
  <personagens>
   <personagem>
    <nome>Sr. Interpretador</nome>
    <ator>Fulano de Tal</ator>
   </personagem>
  </personagens>
  <classificacao tipo="estrelas">5</classificacao>
 </filme>
</filmes>

Veja Também

adicione uma nota

Notas Enviadas por Usuários (em inglês) 7 notes

up
4
Patanjali
8 years ago
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
up
3
booleer at yahoo dot it
13 years ago
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string
= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo
$xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<item id="foo">
<root>
up
2
caffeinatedbits
1 year ago
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml
= <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
<Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo
$animals->Dog->asXML();
// <Dog/>

?>
up
2
caffeinatedbits
1 year ago
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml
= <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
<Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo
$animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
// array(1) {
// ["breed"]=>
// string(9) "chihuahua"
// }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
up
1
p.servus
13 years ago
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml
= new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo
$xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
up
0
caffeinatedbits
1 year ago
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml
= <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
<Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo
$animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
foreach (
$animals->Dog->attributes() as $attr => &$value) {
if (
"breed" === $attr) {
$value = "poodle";
}
}
} catch (
Throwable $e) {
echo
$e->getMessage();
// An iterator cannot be used with foreach by reference
}

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice: Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
// array(1) {
// ["breed"]=>
// string(9) "chihuahua"
// }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice: Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
// ["@attributes"]=>
// array(1) {
// ["breed"]=>
// string(9) "chihuahua"
// }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo
$animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
up
0
sarlak
13 years ago
You can access a node child with his name this way :

<?php
$root
= new SimpleXMLElement($filePath);
echo
$root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
To Top