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

search for in the

DOMNode::cloneNode> <DOMNode
Last updated: Fri, 10 Oct 2008

view this page in

DOMNode::appendChild

(No version information available, might be only in CVS)

DOMNode::appendChild 子要素群の最後に新しい子要素を追加する

説明

DOMNode DOMNode::appendChild ( DOMNode $newnode )

この関数は、既存の子要素のリストに新しい子要素を追加するか、 あるいは新しい子要素リストを作成します。子要素の作成には DOMDocument::createElementDOMDocument::createTextNode などを使用するか、単に別のノードを使用します。

パラメータ

newnode

追加する子要素。

返り値

追加したノードを返します。

エラー / 例外

DOM_NO_MODIFICATION_ALLOWED_ERR

ノードが読み込み専用であったり、挿入するノードの以前の親が 読み込み専用であったりした場合に発生します。

DOM_HIERARCHY_REQUEST_ERR

newnode で指定した型の子ノードを 保持することが許可されていない場合、あるいは追加しようとしている ノードが自分自身やその祖先であった場合に発生します。

DOM_WRONG_DOCUMENT_ERR

newnode が、このノードとは別の ドキュメントで作成されたものである場合に発生します。

以下の例は、新しいドキュメントに新しい要素を追加します。

例1 子要素の追加

<?php

$doc 
= new DOMDocument;

$node $doc->createElement("para");
$newnode $doc->appendChild($node);

echo 
$doc->saveXML();
?>



add a note add a note User Contributed Notes
DOMNode::appendChild
krisdover at hotmail dot com
01-Jun-2008 05:49
What's not mentioned here is that DOMNode::appendChild() can also be used to move an existing node to another part of the DOMDocument, e.g.

<?php
$doc
= new DOMDocument();
$doc->loadXML("<foobar><bar/><foo/></foobar>");
$bar = $doc->documentElement->firstChild;
$foo = $doc->documentElement->lastChild;
$foo->appendChild($bar);
print
$doc->saveXML();
?>

This produces:

<?xml version="1.0"?>
<foobar><foo><bar/></foo></foobar>

Note that the nodes "<foo/>" and "<bar/>" were siblings, i.e. the first and last child of "<foobar>" but using appendChild() we were able to move "<bar/>" so that it is a child of "<foo/>".

This saves you the trouble of doing a DOMNode::removeChild($bar) to remove "<bar/>" before appending it as a child of "<foo/>".

Kris Dover
jrtayloriv at gmail dot com
30-Mar-2008 02:56
If you want to create nested DOM elements:

<?php
    $doc
= new DOMDocument();
   
   
$foo = $doc->createElement("foo");
   
$doc->appendChild($foo);

   
$bar = $doc->createElement("bar");
   
$foo->appendChild($bar);

   
$bazz = $doc->createElement("bazz");
   
$foo->appendChild($bazz);

    echo
$doc->saveXML();
?>

Is equivalent to:

<foo>
  <bar></bar>
  <bazz></bazz>
</foo>

DOMNode::cloneNode> <DOMNode
Last updated: Fri, 10 Oct 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites