If you're looking for a way to append children you may be interested in this:
<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');
$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;
echo 'count child=',$x->count(),"\n";
echo $x->asXML();
foreach ( $x->children() as $foo )
{
var_dump($foo);
}
?>
SimpleXMLElement::addChild
(PHP 5 >= 5.1.3)
SimpleXMLElement::addChild — Añade un elemento hijo al nodo XML
Descripción
public SimpleXMLElement SimpleXMLElement::addChild
( string
$name
[, string $value
[, string $namespace
]] )Añade un elemento hijo al nodo y retorna un SimpleXMLElement del hijo.
Parámetros
-
name -
Nombre del elemento hijo a añadir.
-
value -
Si se especifica, valor del elemento hijo.
-
namespace -
Si se especifica, el namespace al que pertenece el elemento hijo.
Valores devueltos
El método addChild retorna un objeto SimpleXMLElement representando el hijo añadido al nodo XML.
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 sobre Parser');
$pelicula->addChild('argumento', 'Todo sobre las personas que hacen que funcione.');
$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::addAttribute() - Añade un atributo al elemento SimpleXML
- Uso básico de SimpleXML
jerikojerk ¶
1 year ago
alex dot feraud at gmail dot com ¶
1 year ago
Here is a class with more functions for SimpleXMLElement :
<?php
/**
*
* Extension for SimpleXMLElement
* @author Alexandre FERAUD
*
*/
class ExSimpleXMLElement extends SimpleXMLElement
{
/**
* Add CDATA text in a node
* @param string $cdata_text The CDATA value to add
*/
private function addCData($cdata_text)
{
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}
/**
* Create a child with CDATA value
* @param string $name The name of the child element to add.
* @param string $cdata_text The CDATA value of the child element.
*/
public function addChildCData($name,$cdata_text)
{
$child = $this->addChild($name);
$child->addCData($cdata_text);
}
/**
* Add SimpleXMLElement code into a SimpleXMLElement
* @param SimpleXMLElement $append
*/
public function appendXML($append)
{
if ($append) {
if (strlen(trim((string) $append))==0) {
$xml = $this->addChild($append->getName());
foreach($append->children() as $child) {
$xml->appendXML($child);
}
} else {
$xml = $this->addChild($append->getName(), (string) $append);
}
foreach($append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
}
?>
ivan dot kakurov at gmail dot com ¶
4 months ago
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
$xmlDAta = array(
array(
"name" => "nameVal",
"value" => "valVal",
"css" => "cssVal"
),
array(
"name" => "name1Val",
"value" => "val1Val",
"css" => "css1Val"
),
"tname" => array(
array(
"iTname" => "iTname",
"iTname2" => "iTname1",
"iTname2" => "iTname2",
"iTbname3" => array(
"iiTbname" => "tbName",
"iiTbname1" => "tbName1",
),
),
),
"tdata" => "otheerDAta"
);
/**
* Create XML using string or array
*
* @param mixed $data input data
* @param SimpleXMLElement $xml
* @param string $child name of first level child
*
* @return adding Xml formated data into SimpleXmlElement
*/
function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
{
foreach($data as $key => $val) {
if(is_array($val)) {
if(is_numeric($key)) {
$node = $xml->addChild($child);
$nodes = $node->getName($child);
} else {
$node = $xml->addChild($key);
$nodes = $node->getName($key);
}
$node->addChild($nodes, self::data2Xml($val, $node));
} else {
$xml->addChild($key, $val);
}
}
}
//Use
$xml = new SimpleXMLElement("<root/>");
Util::data2XML($xmlDAta, $xml, "Items");
?>
felipenmoura at gmail dot com ¶
2 years ago
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
$xml= new SimpleXMLElement('<root></root>');
$xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
$son= $xml->father->addChild('son'); // uses the first father tag
$son['name']= 'first son';
$otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
$otherSon['name']= 'second son';
echo htmlentities($xml->asXML());
?>
The result will be
<root>
<father>
<son name='first son' />
<son name='second son' />
</father>
</root>
So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.
frosty dot z at freesbee dot fr ¶
3 days ago
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."
To work around that problem, you can use direct property assignment such as :
<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value < > &</value>
?>
instead of doing :
<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value < > &</value> (invalid XML)
?>
See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)
HTH
passerbyxp at gmail dot com ¶
1 month ago
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:
<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/
$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>
Same in PHP 5.3 and 5.4
Volker Grabsch ¶
2 years ago
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".
So addChild() is unsuited to handle user-defined input!
Instead, you will have to replace all "&" with "&" before calling addChild().
Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
_pilip ¶
10 months ago
SimpleXmlElement who works with Soap with ampersand.
<?php
class SoapXMLElement extends SimpleXMLElement
{
public function addChild ($key, $value) {
$value = str_replace('&', '&', $value);
parent::addChild($key, $value);
}
}
?>
pierpaolog at gmail dot com ¶
11 months ago
I found myself doing something like:
<?php
$cn = $contentNode->$name;
?>
and keep getting an error message like:
Warning: SimpleXMLElement::addChild(): Cannot add child. Parent is not a permanent member of the XML tree
I found out that what I needed to do to make the node permanent was:
<?php
$cn = $contentNode->$name = "";
$cn = $contentNode->$name;
?>
hope will help someone else.
