SimpleXMLElement
在线手册:中文 英文
PHP手册

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3)

SimpleXMLElement::addChild Adds a child element to the XML node

说明

public SimpleXMLElement SimpleXMLElement::addChild ( string $name [, string $value [, string $namespace ]] )

Adds a child element to the node and returns a SimpleXMLElement of the child.

参数

name

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

返回值

The addChild method returns a SimpleXMLElement object representing the child added to the XML node.

范例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type''documentary');

$movie $sxe->addChild('movie');
$movie->addChild('title''PHP2: More Parser Stories');
$movie->addChild('plot''This is all about the people who make it work.');

$characters $movie->addChild('characters');
$character  $characters->addChild('character');
$character->addChild('name''Mr. Parser');
$character->addChild('actor''John Doe');

$rating $movie->addChild('rating''5');
$rating->addAttribute('type''stars');
 
echo 
$sxe->asXML();

?>

以上例程的输出类似于:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

参见


SimpleXMLElement
在线手册:中文 英文
PHP手册
PHP手册 - N: Adds a child element to the XML node

用户评论:

jasen at treshna dot com (07-Feb-2012 11:51)

Jerikojerk's example only works with nodes containing only text,

if you run it you will see that in the resulting XML the attributes "pos=..."have been dropped. if you try it with nodes containing other nodes the contained nodes are just ignored and their content is dropped.
It appears that there is an implicit cast to string at the assignment.

using this simplexml DOM method seems to be a waste of time.

$element->{"childname"}[]="stringcontent";

seems to work better in all cases.

done this way  '&','<', and '>' are escaped correctly,
but you still can't graft trees in this way, only single #text nodes.

I'm guessing that some sort of recursion like Alex Feraud uses in his extension is needed to do a full tree grafting operation using simplexml.

as felipenmoura demonstrates it is however relatively simple to work in a top-down direction, growing the XML tree from the root instead of grafting branches on.  addChild gets you a (writable) referenece to the child which is useful, but you had best remeber to escape your content when using addchild
or instead the content to index 0 of the new node reference eg:

given $menuitem is a SimpleXMLElement

instead of
$newnode=$menuitem->addchild("dish",'Fish &amp; Chips");

you can do
$newnode=$menuitem->addchild("dish");
$newode[0]="Fish & Chips";

jerikojerk (31-Jul-2011 03:32)

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);
}

?>

alex dot feraud at gmail dot com (16-Jun-2011 10:52)

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);
            }
        }
    }
}
?>

Volker Grabsch (21-Apr-2011 02:17)

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 "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.

felipenmoura at gmail dot com (12-Apr-2011 02:06)

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.

Dmitry Dulepov (02-Sep-2009 01:53)

addChild will automatically escape all XML characters as necessary. You do not have to do any magic when adding values like "if a > b then...".