DOMDocument->createElement()

(no version information, might be only in CVS)

DOMDocument->createElement() -- Create new element node

说明

class DOMDocument {

DOMElement createElement ( string name [, string value] )

}

This function creates a new instance of class DOMElement. 本节点不会出现在文档中,除非是用例如 DOMNode->appendChild() 函数来将其插入。

参数

name

The tag name of the element.

value

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

返回值

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

异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

范例

例子 1. 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();
?>

上例将输出:

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


add a note add a note User Contributed Notes
inayat_us21 at yahoo dot com
07-Feb-2006 02:05
Simple way to create an rss feed using php5
<?php

//create xml doc
$doc = new DOMDocument("1.0");

//create the rss element
$root = $doc->createElement('rss');
$root = $doc->appendChild($root);
$root->setAttribute('version','2.0');

//create the channel element
$channel = $doc->createElement("channel");
$channel = $root->appendChild($channel);

$elements = array();
$elements["title"] = "my feed's title";
$elements["link"] = "http://mydomain.com/index.rss";
$elements["description"] = "Demonstration feed created using PHP5 and the DOM extension. The php script that generated this document can be found at : http://thousandrobots.com/dev/xml/dom/auto.phps";
$elements["language"] = "en-us";
$elements["copyright"] = "copyright 2005 thousandrobots.com";
$elements["docs"] = "http://backend.userland.com/rss";
$elements["generator"] = "thousand robots dom-based rss generator";
$elements["managingEditor"] = "editor@spam.thousandrob0ts.com (ADM)";
$elements["webMaster"] = "webmaster@spam.thousandrob0ts.com (ADM)";
$elements["lastBuildDate"] = "Sat, 05 Feb 2005 23:39:07 EST";

foreach (
$elements as $elementname => $elementvalue)
{
 
$elementname = $doc->createElement($elementname);
 
$elementname = $channel->appendChild($elementname);
 
$elementname->appendChild($doc->createTextNode($elementvalue));
}

//clear the array
unset($elements);

//now create the first feed item
//instead, you could just pull some items from a db into an elements[] array.
$elements[0]["title"] = "title of first item";
$elements[0]["description"] = "a short description of the first item";
$elements[0]["link"] = "http://thousandrobots.com/?article=1";
$elements[0]["author"] = "author@spam.thousandrob0ts.com (ADM)";
$elements[0]["pubDate"] = "Sat, 05 Feb 2005 23:39:07 EST";
$elements[0]["category"] = "tech";
$elements[0]["guid"] = "http://thousandrobots.com/?article=1";

//create the other items
$elements[1]["title"] = "title of next item";
$elements[1]["description"] = "a short description of the next item";
$elements[1]["link"] = "http://thousandrobots.com/?article=N";
$elements[1]["author"] = "author@spam.thousandrob0ts.com (ADM)";
$elements[1]["pubDate"] = "Sat, 05 Feb 2005 22:39:07 EST";
$elements[1]["category"] = "tech";
$elements[1]["guid"] = "http://thousandrobots.com/?article=N";

//loop through each item and add its elements to the tree
foreach ( $elements as $element )
{
  
//create the item element
  
$item = $doc->createElement("item");
  
$item = $channel->appendChild($item);
  
   foreach (
$element as $elementname => $elementvalue )
   {
      
$elementname = $doc->createElement($elementname);
      
$elementname = $item->appendChild($elementname);
      
$elementname->appendChild($doc->createTextNode($elementvalue));
   }
}

//output the xml
header('Content-Type: text/xml');
echo
$doc->saveXML();

?>
php at pureftpd dot org
15-Aug-2005 07:40
What is missing from the documentation is that arguments for createElement() *must* be escaped with htmlspecialchars().

Without it, "&" characters will produce invalid XML.
brian dot sanders at cometsystems dot com
21-Jan-2005 06:08
Regarding paul squigly-symbol allofus dot org's comment below:

Neither this method, nor setting the nodeValue property, encodes ampersands (&).  You must manually encode them or use the textContent property (which encodes them as expected.)

However, setting textContent on an element created by DOMDocument::createElement does NOT work.  You must create a text node, set its textContent, then append the text node to your element:

<?php

$dom
= DomDocument::loadXML(<<<XML
<?xml version="1.0"?>
<foo/>
XML)
;

$element = $dom->createElement('bar');
$element->appendChild($dom->createTextNode('pb & j'));
$dom->documentElement->appendChild($element);

?>
franp at free dot fr
05-Aug-2004 05:02
AFAIK there is no way to return as a string a newly created node or element before attaching it to an existing DOMDocument.

If you need to display a newly created node or element for debugging purposes - certainly you will at some point :-( , you must temporary append it to an existing DOMDocument.

Example :
<?php
$newQuant
= $caddy->createElement("quantity");
$newQuantText = $caddy->createTextNode("5");
$newQuant->appendChild($newQuantText);
?>

// Until now no way to check the result
// Let's append it to an existing DOMDocument :
<?php
$caddy
->documentElement->appendChild($newQuant);   
?>

// Now we can display it as a string :
<?php
echo nl2br(htmlspecialchars(
$caddy->saveXML($caddy->documentElement->lastChild)));
?>

// This return :
<?php
<quantity>5</quantity>
?>
       
// Do not forget to remove the appended node as it may  :
<?php
$caddy
->documentElement->removeChild($newQuant);
?>

That's it !
It is a convenient workaround for the lack of "transformToXML" in php5.