PHP addChild() Function

Definition and Usage

The addChild() function adds a child node to the specified XML node.

This function returns a SimpleXMLElement object that represents the child element added to the XML node.

Syntax

class SimpleXMLElement
{
string addChild(name,value,ns)
}
Parameter Description
name Required. Specify the name of the child element.
value Required. Specify the value of the child element.
ns Optional. Specify the namespace of the child element.

Example

XML File:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP Code:

<?php
$xml = simplexml_load_file("test.xml");
$xml->body[0]->addChild("date", "2008-08-08");
foreach ($xml->body->children() as $child)
  {
  echo "Child node: " . $child;
  }
?>

Output:

Child node: 2008-08-08