array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'ja', ), 'this' => array ( 0 => 'domdocument.createelementns.php', 1 => 'DOMDocument::createElementNS', ), 'up' => array ( 0 => 'class.domdocument.php', 1 => 'DOMDocument', ), 'prev' => array ( 0 => 'domdocument.createelement.php', 1 => 'DOMDocument::createElement', ), 'next' => array ( 0 => 'domdocument.createentityreference.php', 1 => 'DOMDocument::createEntityReference', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'ja', 'path' => 'reference/dom/domdocument/createelementns.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5, PHP 7, PHP 8)
DOMDocument::createElementNS — 関連付けられた名前空間に新しい要素を作成する
$namespace
, string $qualifiedName
, string $value
= ""): DOMElement|falseこの関数は、関連付けられた名前空間に新しい要素を作成します。 このノードは、( DOMNode::appendChild() などで) 挿入されない限り、ドキュメント内にあらわれません。
namespace
名前空間の URI。
qualifiedName
要素名を、prefix:tagname
のような形式で指定する。
value
要素の値。デフォルトでは、空の要素が作成されます。 その後に DOMElement::$nodeValue で値を設定することも可能です。
新しい DOMElement、
あるいはエラーが発生した場合には false
を返します。
DOM_INVALID_CHARACTER_ERR
qualifiedName
が無効な文字を含んでいる場合に発生します。
DOM_NAMESPACE_ERR
qualifiedName
が無効な名前である場合に発生します。
例1 新しい要素を作成し、ルートとして挿入する
<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');
// 新しい要素をルート (ドキュメントの子要素) として挿入する
$dom->appendChild($element);
echo $dom->saveXML();
?>
上の例の出力は以下となります。
<?xml version="1.0" encoding="iso-8859-1"?> <xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>
例2 名前空間プレフィックスの例
<?php
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);
echo $doc->saveXML(), "\n";
echo $item->namespaceURI, "\n"; // 出力: http://base.google.com/ns/1.0
echo $item->prefix, "\n"; // 出力: g
echo $item->localName, "\n"; // 出力: item_type
?>
上の例の出力は以下となります。
<?xml version="1.0" encoding="utf-8"?> <element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"> <g:item_type>house</g:item_type> </element> http://base.google.com/ns/1.0 g item_type