首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

DOMDocument::createElementNS

(PHP 5, PHP 7)

DOMDocument :: createElementNS - 使用关联的名称空间创建新的元素节点

描述

代码语言:javascript
复制
public DOMElement DOMDocument::createElementNS ( string $namespaceURI , string $qualifiedName [, string $value ] )

该函数用相关的名称空间创建一个新的元素节点。除非使用(例如)DOMNode :: appendChild()插入,否则该节点不会显示在文档中。

参数

namespaceURI

命名空间的URI。

qualifiedName

元素的限定名称,作为前缀:标记名

value

元素的值。默认情况下,将创建一个空元素。您也可以稍后使用DOMElement :: $ nodeValue设置值。

返回值

新的DOMElement或FALSE发生错误。

错误/异常

DOM_INVALID_CHARACTER_ERR

如果qualifiedName包含无效字符则引发。

DOM_NAMESPACE_ERR

如果qualifiedName是模糊的限定名称则引发。

例子

示例#1创建一个新元素并将其作为根插入

代码语言:javascript
复制
<?php

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

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

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

echo $dom->saveXML();
?>

上面的例子将输出:

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

示例#2名称空间前缀示例

代码语言:javascript
复制
<?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"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n";       // Outputs: g
echo $item->localName, "\n";    // Outputs: item_type
?>

上面的例子将输出:

代码语言:javascript
复制
<?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

扫码关注腾讯云开发者

领取腾讯云代金券