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);
?>
SimpleXMLElement::addAttribute
(PHP 5 >= 5.1.3)
SimpleXMLElement::addAttribute — Añade un atributo al elemento SimpleXML
Descripción
public void SimpleXMLElement::addAttribute
( string
$name
[, string $value
[, string $namespace
]] )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 namespace al que pertenece el atributo.
Valores devueltos
No devuelve ningún valor.
Ejemplos
Nota:
Los ejemplos listados quizá incluyen example.php, que hacen referencia a la cadena XML encontrada en el primer ejemplo de la guía de uso básico.
Ejemplo #1 Añade 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 type="estrellas">5</puntuacion>
</pelicula>
</peliculas>
Ver también
- SimpleXMLElement::addChild() - Añade un elemento hijo al nodo XML
- Uso básico de SimpleXML
sarlak ¶
2 years ago
p.servus ¶
1 year 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>
booleer at yahoo dot it ¶
2 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>
