PHP Function Reference

PHP SimpleXMLElement - addChild() Method



The PHP SimpleXMLElement::addChild() method adds a child element to the XML node and returns a SimpleXMLElement of the child.

Syntax

public SimpleXMLElement::addChild(qualifiedName, value, namespace)

Parameters

qualifiedName Required. Specify the name of the child element to add.
value Optional. If specified, the value of the child element.
namespace Optional. If specified, the namespace to which the child element belongs.

Return Value

Returns a SimpleXMLElement object representing the child added to the XML node on success or null on failure.

Example:

The example below shows the usage of SimpleXMLElement::addChild() method.

<?php
$xmlstr = <<<XML
<userlist> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
  </user>
</userlist> 
XML;

$xml = simplexml_load_string($xmlstr);

$xml->addAttribute('type', 'games');

$user = $xml->addChild('user');
$user->addAttribute('id', 'Marry2015');
$user->addAttribute('game', 'group');

$name = $user->addChild('name', 'Marry G.');

$city = $user->addChild('city', 'London');

echo $xml->asXML();
?>

The output of the above code will be similar to:

<userlist type="games"> 
  <user id="John123" game="lonely">
    <name>John Smith</name>
    <city>New York</city>
  </user>
  <user id="Marry2015" game="group">
    <name>Marry G.</name>
    <city>London</city>
  </user>
</userlist>

❮ PHP SimpleXML Reference