Наш чат в Telegram для обмена идеями, проектами, мыслями, людьми в сфере ИТ г.Ростова-на-Дону: @it_rostov

DOMDocument::createElement

(PHP 5)

DOMDocument::createElement — Создает новый узел-элемент


Описание

public DOMElement DOMDocument::createElement ( string $name [, string $value ] )

Эта функция создает экземпляр класса DOMElement. Этот узел не будет отображаться в документе до тех пор, пока он не будет вставлен, например, функцией DOMNode::appendChild().


Список параметров

name

- Имя элемента.

value

- Значение элемента. По умолчанию будет создан пустой элемент. Значение может быть установлено позднее с помощью функции DOMElement::$nodeValue.


Возвращаемые значения

Возвращает новый объект класса DOMElement либо FALSE в случае ошибки.


Ошибки

DOM_INVALID_CHARACTER_ERR

- Возникает, если name содержит недопустимые символы.


Примеры

Пример #1 Создание нового элемента и вставка его в качестве корневого

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('test', 'This is the root element!');
// Вставляем новый элемент как корень (потомок документа)
$dom->appendChild($element);
echo $dom->saveXML();

Результат выполнения данного примера:


<?xml version="1.0" encoding="utf-8"?>
<test>Это корневой элемент!</test>


Примечания

Замечание:

Значение value не будет экранировано. Используйте функцию DOMDocument::createTextNode() для создания узла с текстовым содержимым с поддержкой экранирования.


Смотрите также


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();


4
funkathustra2 years ago
  $div = $dom->createElement("div");
  $div->setAttribute("class","MyClass");
  $div->setAttribute("id","MyID");
  $someOtherDiv->appendChild($div);


4
sergsokolenko at gmail dot com8 years ago
//...
$dom->createElement('name', htmlentities($text))
//...


1
lars dot c dot magnusson at gmail dot com4 years ago
$dom = new DOMDocument(); 
$dom->load($file);
$dom->appendChild($newNode); //Works fine
$dom->insertBefore($newNode, $refNode); //Will fail
$refNode->parentNode->insertBefore($newNode, $refNode); // thanx to yasindagli (first post)


1
estill at gvtc dot com7 years ago
$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();


1
chris AT cmbuckley DOT co DOT uk5 years ago
$dom = new DOMDocument('1.0', 'utf-8');
$el = $dom->createElement('foo' . "\0" . 'bar', 'Hello World');
echo $el->tagName; // outputs "foo"


1
yasindagli at gmail dot com5 years ago
function createElement($domObj, $tag_name, $value = NULL, $attributes = NULL)
{
    $element = ($value != NULL ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);
    if( $attributes != NULL )
    {
        foreach ($attributes as $attr=>$val)
        {
            $element->setAttribute($attr, $val);
        }
    }
    return $element;
}
$dom = new DOMDocument('1.0', 'utf-8');
$elm = createElement($dom, 'foo', 'bar', array('attr_name'=>'attr_value'));
$dom->appendChild($elm);
echo $dom->saveXML();


Описание класса domdocument, примеры использования класса domdocument.

Описание на ru2.php.net
Описание на php.ru