SimpleXMLElement::addAttribute

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

SimpleXMLElement::addAttribute Añade un atributo al elemento SimpleXML

Descripción

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

Añade un atributo al elemento SimpleXML.

Parámetros

name

El nombre del atributo a añadir.

value

El valor del atributo.

namespace

Si se especifica, indica el espacio de nombres al que pertenece el atributo.

Valores devueltos

No devuelve ningún valor.

Ejemplos

Nota:

Los ejemplos enumerados podrían incluir example.php, que hace referencia al string XML encontrado en el primer ejemplo de la guía de uso básico.

Ejemplo #1 Añadir atributos e hijos a un elemento SimpleXML

<?php

include 'example.php';
 
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('tipo''documental');

$pelicula $sxe->addChild('pelicula');
$pelicula->addChild('titulo''PHP2: Más historias del Parser');
$pelicula->addChild('argumento''Todo sobre la gente que lo hace funcionar.');

$personajes $pelicula->addChild('personajes');
$personaje  $personajes->addChild('personaje');
$personaje->addChild('nombre''Sr. Parser');
$personaje->addChild('actor''John Doe');

$puntuacion $pelicula->addChild('puntuacion''5');
$puntuacion->addAttribute('tipo''estrellas');
 
echo 
$sxe->asXML();

?>

El resultado del ejemplo sería algo similar a:

<?xml version="1.0" standalone="yes"?>
<peliculas tipo="documental">
 <pelicula>
  <titulo>PHP: Tras el Parser</titulo>
  <personajes>
   <personaje>
    <nombre>Srta. Programadora</nombre>
    <actor>Onlivia Actora</actor>
   </personaje>
   <personaje>
    <nombre>Sr. Programador</nombre>
    <actor>El Actor</actor>
   </personaje>
  </personajes>
  <argumento>
   Así que, este lenguaje. Es como, un lenguaje de programación. ¿O es un
   lenguaje interpretado? Lo descubrirás en esta intrigante y temible parodia
   de un documental.
  </argumento>
  <grandes-lineas>
   <linea>PHP soluciona todos los problemas web</linea>
  </grandes-lineas>
  <puntuacion tipo="pulgares">7</puntuacion>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
 <pelicula>
  <titulo>PHP2: Más historias del Parser</titulo>
  <argumento>Todo sobre la gente que lo hace funcionar.</argumento>
  <personajes>
   <personaje>
    <nombre>Sr. Parser</nombre>
    <actor>John Doe</actor>
   </personaje>
  </personajes>
  <puntuacion tipo="estrellas">5</puntuacion>
 </pelicula>
</peliculas>

Ver también

add a note add a note

User Contributed Notes 4 notes

up
4
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
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
2
p.servus
12 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
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