downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

DomNode::append_sibling> <DomNode::add_namespace
[edit] Last updated: Fri, 25 May 2012

view this page in

DomNode::append_child

(PHP 4 >= 4.1.0)

DomNode::append_child Agrega un nuevo hijo al final de los hijos

Descripción

DOMNode DOMNode::append_child ( DOMNode $newnode )

Esta función agrega un hijo a la lista existente de hijos o crea una nueva lista de hijos.

Parámetros

newnode

El nodo que será anexado. Este puede ser creado por ejemplo con: DomDocument::create_element, DomDocument::create_text_node etc. o simplemente utilizando cualquier otro nodo.

Nota:

No puede anexar un DOMAttribute utilizando este método. Use DomElement::set_attribute en su lugar.

Valores devueltos

Retorna el nodo anexado cuando se ejecuta correctamente o FALSE en caso de error.

Historial de cambios

Versión Descripción
4.3.0 Ya no está permitido insertar un nodo desde otro documento.
4.3.0 Previo a PHP 4.3.0, el nuevo hijo es duplicado antes de ser agregado. Por lo tanto el nuevo hijo es una copia completamente nueva la que puede ser modificada sin cambiar el nodo que fue pasado a la función. Si el nodo pasado tiene hijos, ellos serán duplicados también, lo que hace fácil duplicar gran parte de un ducumento XML. El valor de retorno es el hijo agregado. Si planea hacer futuras modificaciones sobre el hijo agregado debe utilizar el nodo retornado.
4.3.0 y 4.3.1 El nuevo hijo newnode es primero desligado de su contexto existente, si ya es un hijo de DomNode. Por lo tanto el newnode es movido y no copiado. Este es el comportamiento de acuerdo a las especificaciones de la W3C. Si necesita el comportamiento antiguo, use DomNode::clone_node antes de agregar.
4.3.2 El nuevo hijo newnode es primero desligado de su contexto existente, si ya está en un árbol. Las mismas reglas aplican.

Ejemplos

El siguiente ejemplo agrega un nuevo nodo elemento a un documento vacío y establece el atributo align a left.

Ejemplo #1 Agregando un hijo

<?php
$doc 
domxml_new_doc("1.0");
$node $doc->create_element("para");
$newnode $doc->append_child($node);
$newnode->set_attribute("align""left");
?>

El ejemplo de arriba puede también escribirse como sigue:

Ejemplo #2 Agregando un hijo

<?php
$doc 
domxml_new_doc("1.0");
$node $doc->create_element("para");
$node->set_attribute("align""left");
$newnode $doc->append_child($node);
?>

Un ejemplo más complejo es el que sigue a continuación. Primero busca un cierto elemento, lo duplica incluyendo sus hijos y los agrega como hermanos. Finalmente un nuevo atributo es agregado a uno de los hijos del nuevo hermano y el documento en su totalidad es eliminado.

Ejemplo #3 Agregando un hijo

<?php
include("example.inc");

if (!
$dom domxml_open_mem($xmlstr)) {
  echo 
"Error durante el análisis del documento\n";
  exit;
}

$elements $dom->get_elements_by_tagname("informaltable");
print_r($elements);
$element $elements[0];

$parent $element->parent_node();
$newnode $parent->append_child($element);
$children $newnode->children();
$attr $children[1]->set_attribute("align""left");

$xmlfile $dom->dump_mem();
echo 
htmlentities($xmlfile);
?>

El ejemplo de anterior también puede ser hecho con DomNode::insert_before en lugar de DomNode::append_child.

Para migrar a PHP 5

Debe usar DOMNode::appendChild.



add a note add a note User Contributed Notes DomNode::append_child
andrew at transitionmedia dot co dot uk 12-Feb-2006 07:03
As of version 4.3 PHP doesn't support Appending a child from another source document. If you are trying to  import information from multiple sources into a final document [for transformation using XSL as an example] then you can have problems. This technique can be used to do it though.

I am assuming you have two documents open, $xmldoc1 and $xmldoc2 and you have selected [via XPath or explicit searching] the nodes you want in each document. Thus $xmldoc1_appending_node is the node you would like to add $xmldoc2_importnode to.

<?

// first we create a temporary node within the document we want to add to.
$temp_importnode = $xmldoc1->create_element("import");

// now we have a node that is in the right document context we can clone the one we want into this one.
$temp_importnode = $xmldoc_importnode->clone_node(true);

// by using true in the above call to clone_node() we copy all of the child nodes as well. Use false or nothing if you just want the containing node with no children.

$xmldoc1_appending->append_child($importnode);

?>

Now your document contains the new nodes imported from a different document.
wackysalut at bourget dot cc 01-Nov-2002 12:46
Be careful of the order you append childs. (PHP <= 4.2)

If you create let's say:

$x_html = $x_doc->create_element('html');
$x_head, $x_title, $x_meta, $x_link and $x_body in the same way.

If you:

$x_head->append_child($x_title);
$x_head->append_child($x_meta);
$x_head->append_child($x_link);

$x_html->append_child($x_head);

$x_body_backup = $x_html->append_child($x_body);

/* here */

$x_doc->append_child($x_html);

If you now try to modify $x_body_backup.. it will no longer be able to modify the actualy XML tree, because you appended the HTML tree to the DomDocument.. and it has copied ALL the nodes at the end of the DomDocument, so the reference you now have in $x_body_backup is not valid anymore! If you had modified it where the /* here */ line is.. the $x_body_backup would still be valid.. but not after the $x_doc->append_child($x_html);

What you can do is, reverse the order of your appendings.. so that you append the highest level node at the end.. so that your reference is still valid after, or wait till you have filled all of the nodes you wanted to add before you append it to your parent node.

 
show source | credits | sitemap | contact | advertising | mirror sites