函数名称:DOMDocument::createAttributeNS()
适用版本:PHP 5, PHP 7
用法:
DOMDocument::createAttributeNS() 方法用于在指定的命名空间(namespace)和命名空间前缀(prefix)下创建一个新的属性节点(attribute node)。
语法:
public DOMAttr DOMDocument::createAttributeNS ( string $namespaceURI , string $qualifiedName )
参数:
$namespaceURI
:属性节点的命名空间URI。如果不希望指定命名空间,请传递一个空字符串。$qualifiedName
:属性节点的限定名称(包含命名空间前缀和本地名称)。例如,'prefix:localname'。
返回值:
- 成功时,返回一个 DOMAttr 对象,表示所创建的属性节点。如果创建失败,则返回 false。
示例:
// 创建一个新的 DOM Document 对象
$doc = new DOMDocument('1.0', 'UTF-8');
// 创建一个命名空间前缀为 'example',命名空间为 'http://www.example.com' 的属性节点
$attr = $doc->createAttributeNS('http://www.example.com', 'example:attr');
// 设置属性节点的值
$attr->value = 'example value';
// 将属性节点添加到元素节点中
$element = $doc->createElement('example:element');
$element->appendChild($attr);
// 输出 XML
echo $doc->saveXML();
输出结果:
<?xml version="1.0" encoding="UTF-8"?>
<example:element xmlns:example="http://www.example.com" example:attr="example value"/>
以上示例演示了如何使用 DOMDocument::createAttributeNS()
方法创建一个属性节点,并将其添加到元素节点中。在例子中,我们使用了命名空间前缀为 'example',命名空间为 'http://www.example.com'。输出的 XML 结果中,可以看到生成的属性节点被正确地添加到了元素节点中,并且包含了命名空间前缀和命名空间URI的信息。