W3docs

addChild()

Learn how the PHP SimpleXMLElement::addChild() method adds child elements to an XML document, including values, namespaces, gotchas, and runnable examples.

Introduction

SimpleXMLElement::addChild() is the method you use to build XML from scratch in PHP, node by node. SimpleXML is a built-in PHP extension that turns an XML document into an object you can read and write with ordinary property syntax. Where reading is as simple as $xml->book->title, writing a brand-new element is the job of addChild().

This page covers what addChild() returns and why that matters, how to add values and namespaces, and the gotchas that trip people up (entity escaping, attributes vs. elements, and the NULL-value pitfall). Each example below is runnable.

Syntax

public SimpleXMLElement::addChild(
    string $qualifiedName,
    ?string $value = null,
    ?string $namespace = null
): ?SimpleXMLElement
  • $qualifiedName — the name (tag) of the new child element, e.g. "title".
  • $value — optional text content for the element. If omitted or null, an empty element is created (<title/>).
  • $namespace — optional namespace URI the child belongs to.

The return value is the key detail: addChild() returns the newly created child element, not the parent. That returned object is what you chain further calls onto to build nested structures.

Adding a single child

php— editable, runs on the server

This prints:

<?xml version="1.0"?>
<books><book>PHP Basics</book></books>

We start from a root <books> element, then add one <book> child whose text content is PHP Basics. asXML() serializes the object back into an XML string.

Building a nested structure

Because addChild() returns the child it just created, you capture that return value to keep adding deeper levels:

<?php

$xml  = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book');          // returns the <book> element
$book->addChild('title', 'PHP Basics');  // adds <title> inside <book>
$book->addChild('author', 'John Doe');   // adds <author> inside <book>

echo $xml->asXML();

Output:

<?xml version="1.0"?>
<books><book><title>PHP Basics</title><author>John Doe</author></book></books>

If you had called $xml->addChild('title', ...) instead of $book->addChild(...), the <title> would have landed next to <book> rather than inside it. The object you call addChild() on is always the parent.

Children vs. attributes

addChild() only creates elements. To add an attribute (e.g. id="1"), use addAttribute() on the same element:

<?php

$xml  = new SimpleXMLElement('<books></books>');
$book = $xml->addChild('book');
$book->addAttribute('id', '1');
$book->addChild('title', 'PHP Basics');

echo $xml->asXML();

Output:

<?xml version="1.0"?>
<books><book id="1"><title>PHP Basics</title></book></books>

Special characters: a real gotcha

You might expect addChild() to escape XML-unsafe characters in the value for you. It does not fully do so — passing a raw & makes SimpleXML treat it as the start of an entity reference and emit a "unterminated entity reference" warning, dropping the content:

<?php

$xml = new SimpleXMLElement('<docs></docs>');
$xml->addChild('note', 'Tom & Jerry <fun>'); // Warning: unterminated entity reference

echo $xml->asXML();

This prints an empty element, not the text you wanted:

<?xml version="1.0"?>
<docs><note/></docs>

The reliable way to set text containing &, <, or > is property assignment, which escapes correctly:

<?php

$xml = new SimpleXMLElement('<docs></docs>');
$xml->note = 'Tom & Jerry <fun>';

echo $xml->asXML();

Output:

<?xml version="1.0"?>
<docs><note>Tom &amp; Jerry &lt;fun&gt;</note></docs>

So: use addChild() to create the element, but assign untrusted/special-character text through the property (or pre-escape with htmlspecialchars() before passing it in).

Adding namespaced children

The third argument associates the child with a namespace URI:

<?php

$xml = new SimpleXMLElement('<feed xmlns:dc="http://purl.org/dc/elements/1.1/"></feed>');
$xml->addChild('creator', 'Jane Roe', 'http://purl.org/dc/elements/1.1/');

echo $xml->asXML();

Output:

<?xml version="1.0"?>
<feed xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:creator>Jane Roe</dc:creator></feed>

Common gotchas

  • Don't ignore the return value when nesting. addChild() returns the new child; chain on that, not on the root, or your elements end up flat.
  • null vs. empty string. addChild('tag') and addChild('tag', null) both create an empty self-closing element (<tag/>). Pass '' for an empty-but-present text node.
  • Values aren't safely escaped. A raw & in the value triggers an entity-reference warning and loses the text; assign special-character content via the property ($el->tag = $text;) or pre-escape it. Element names must be valid XML identifiers.
  • It mutates in place. addChild() changes the document the object wraps; there's no separate "save" step beyond serializing with asXML().

When to use it

Reach for addChild() whenever you need to generate XML — building an RSS/Atom feed, a sitemap, a configuration file, or an API payload — and you already like SimpleXML's lightweight object syntax. For parsing existing XML you'd typically start with simplexml_load_string() or simplexml_load_file(), then read with children(). For documents that need heavy editing (moving/removing nodes), the DOM extension is a better fit.

Conclusion

SimpleXMLElement::addChild() adds a child element to an XML node and returns that new child so you can build nested trees fluently. Remember the essentials: it returns the child, raw special characters in the value need property assignment or pre-escaping, attributes need addAttribute(), and the optional third argument places the child in a namespace. See PHP SimpleXML for the bigger picture of working with XML in PHP.

Practice

Practice
What is true about the addChild() function in PHP according to the information provided on the specified webpage?
What is true about the addChild() function in PHP according to the information provided on the specified webpage?
Was this page helpful?