Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : DOM Functions : DOMDocument->createElement()

DOMDocument->createElement()

Create new element node ()

Example 517. Creating a new element and inserting it as root

<?php

$dom
= new DOMDocument('1.0', 'iso-8859-1');

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

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

echo
$dom->saveXML();
?>

The above example will output:

<?xml version="1.0" encoding="iso-8859-1"?>
<test>This is the root element!</test>

Related Examples ( Source code ) » dom domdocument createelement



Code Examples / Notes » dom domdocument createelement

mikek dot nospam

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.
<?php
class XDOMElement extends DOMElement {
   function __construct($name, $value = null, $namespaceURI = null) {
       parent::__construct($name, null, $namespaceURI);
   }
}
class XDOMDocument extends DOMDocument {
   function __construct($version = null, $encoding = null) {
       parent::__construct($version, $encoding);
       $this->registerNodeClass('DOMElement', 'XDOMElement');
   }
   function createElement($name, $value = null, $namespaceURI = null) {
       $element = new XDOMElement($name, $value, $namespaceURI);
       $element = $this->importNode($element);
       if (!empty($value)) {
           $element->appendChild(new DOMText($value));
       }
       return $element;
   }
}
$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo $doc1->saveXML();
$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo $doc2->saveXML();
?>
Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>
Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>


sergsokolenko

To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>


estill

Note that the second parameter (value), although convenient, is non-standard. You should create elements like this instead:
<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');
$root = $doc->createElement('test');
$doc->appendChild($root);
$root_text = $doc->createTextNode('This is the root element!');
$root->appendChild($root_text);
print $doc->saveXML();
?>
Or, alternatively, extend the DOMDocument class and add your own custom, convenience method to avoid intruding on the standard:
<?php
class CustomDOMDocument extends DOMDocument {
 function createElementWithText($name, $child_text) {
   // Creates an element with a child text node
   
   // @param  string  $name        element tag name
   // @param  string  $child_text  child node text
   
   // @return  object  new element
   
   $element = $this->createElement($name);
   
   $element_text = $this->createTextNode($child_text);
   $element->appendChild($element_text);
   
   return $element;
 }
}
$doc = new CustomDOMDocument('1.0', 'iso-8859-1');
$root = $doc->createElementWithText('test', 'This is the root element!');
$doc->appendChild($root);
print $doc->saveXML();
?>
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.


poison

In response to 'mikek dot nospam at nospam dot muonics dot com', here is a more correct version, as values have to be UTF-8 encoded, and there's absolutely no reason to create an extra DOMElement class.
<?php
class ADOMDocument extends DOMDocument {
function __construct($version = null, $encoding = null) {
parent::__construct($version, $encoding);
}
public function createElement($tagName, $value=null) {
$node=parent::createElement($tagName);
if (!is_null($value)) {
$node->appendChild(
$this->createTextNode(utf8_encode($value))
);
}
return $node;
}

public function createElementNS($namespaceURI, $qualifiedName, $value=null) {
$node=parent::createElementNS($namespaceURI, $qualifiedName);
if (!is_null($value)) {
$node->appendChild(
$this->createTextNode(utf8_encode($value))
);
}
return $node;
}
}
?>


Change Language


Follow Navioo On Twitter
DOMAttr->__construct()
DOMAttr->isId()
DOMCharacterData->appendData()
DOMCharacterData->deleteData()
DOMCharacterData->insertData()
DOMCharacterData->replaceData()
DOMCharacterData->substringData()
DOMComment->__construct()
DOMDocument->__construct()
DOMDocument->createAttribute()
DOMDocument->createAttributeNS()
DOMDocument->createCDATASection()
DOMDocument->createComment()
DOMDocument->createDocumentFragment()
DOMDocument->createElement()
DOMDocument->createElementNS()
DOMDocument->createEntityReference()
DOMDocument->createProcessingInstruction()
DOMDocument->createTextNode()
DOMDocument->getElementById()
DOMDocument->getElementsByTagName()
DOMDocument->getElementsByTagNameNS()
DOMDocument->importNode()
DOMDocument->load()
DOMDocument->loadHTML()
DOMDocument->loadHTMLFile()
DOMDocument->loadXML()
DOMDocument->normalizeDocument()
DOMDocument->registerNodeClass()
DOMDocument->relaxNGValidate()
DOMDocument->relaxNGValidateSource()
DOMDocument->save()
DOMDocument->saveHTML()
DOMDocument->saveHTMLFile()
DOMDocument->saveXML()
DOMDocument->schemaValidate()
DOMDocument->schemaValidateSource()
DOMDocument->validate()
DOMDocument->xinclude()
DOMDocumentFragment->appendXML()
DOMElement->__construct()
DOMElement->getAttribute()
DOMElement->getAttributeNode()
DOMElement->getAttributeNodeNS()
DOMElement->getAttributeNS()
DOMElement->getElementsByTagName()
DOMElement->getElementsByTagNameNS()
DOMElement->hasAttribute()
DOMElement->hasAttributeNS()
DOMElement->removeAttribute()
DOMElement->removeAttributeNode()
DOMElement->removeAttributeNS()
DOMElement->setAttribute()
DOMElement->setAttributeNode()
DOMElement->setAttributeNodeNS()
DOMElement->setAttributeNS()
DOMElement->setIdAttribute()
DOMElement->setIdAttributeNode()
DOMElement->setIdAttributeNS()
DOMEntityReference->__construct()
DOMImplementation->__construct()
DOMImplementation->createDocument()
DOMImplementation->createDocumentType()
DOMImplementation->hasFeature()
DOMNamedNodeMap->getNamedItem()
DOMNamedNodeMap->getNamedItemNS()
DOMNamedNodeMap->item()
DOMNode->appendChild()
DOMNode->cloneNode()
DOMNode->hasAttributes()
DOMNode->hasChildNodes()
DOMNode->insertBefore()
DOMNode->isDefaultNamespace()
DOMNode->isSameNode()
DOMNode->isSupported()
DOMNode->lookupNamespaceURI()
DOMNode->lookupPrefix()
DOMNode->normalize()
DOMNode->removeChild()
DOMNode->replaceChild()
DOMNodelist->item()
DOMProcessingInstruction->__construct()
DOMText->__construct()
DOMText->isWhitespaceInElementContent()
DOMText->splitText()
DOMXPath->__construct()
DOMXPath->evaluate()
DOMXPath->query()
DOMXPath->registerNamespace()
dom_import_simplexml
eXTReMe Tracker