Parameters

name

The tag name of the element.

value

The value of the element. By default, an empty element will be created.
The value can also be set later with DOMElement::$nodeValue.

The value is used verbatim except that the < and > entity
references will escaped. Note that & has to be manually escaped;
otherwise it is regarded as starting an entity reference. Also " won't be
escaped.

Return Values

Returns a new instance of class DOMElement or FALSE
if an error occurred.

Errors/Exceptions

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

Examples

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)$dom->appendChild($element);

User Contributed Notes 9 notes

With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct. If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &amp;s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor. Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

Also use caution with (or avoid) the 'DOMElement->nodeValue' property. It can return some unexpected values and changing its value will replace (remove) all descendants of the element with a single text node. It's also non-standard; according to the DOM spec it should return NULL.

Although the built-in DOM functions are great, since they're designed to support generic XML, generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically speed things up.Instead of calling something like<?php $div = $dom->createElement("div");$div->setAttribute("class","MyClass");$div->setAttribute("id","MyID");$someOtherDiv->appendChild($div);?>you can accomplish the same thing with:<?php $div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");?>The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold up if your content has those characters in it. So, you can also pass it an array:<?php $div = newElement("div", $someOtherDiv, array("class","MyClass"));?>Or an array of arrays, representing different attributes:<?php $div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");?>