DOMElement::setAttributeNS()函数是PHP中的内置函数,用于将具有给定名称空间和名称的属性设置为给定值。如果该属性不存在,则将创建它。
用法:
void DOMElement::setAttributeNS( string $namespaceURI, string $qualifiedName, string $value )
参数:此函数接受上述和以下所述的三个参数:
- $namespaceURI:它指定名称空间URI。
 - $qualifiedName:它指定属性的名称。
 - $value:它指定属性的值。
 
返回值:此函数不返回任何内容。
异常:如果节点是只读节点或DOM_NAMESPACE_ERR,或者$qualifiedName是格式错误的合格名称,或者$qualifiedName具有前缀并且namespaceURI为NULL,则此函数将抛出DOM_NO_MODIFICATION_ALLOWED_ERR。
以下示例说明了PHP中的DOMElement::setAttributeNS()函数:
范例1:
<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
   
// Create an element 
$node = $dom->createElementNS("my_namespace", "x:p",  
                     'Hello, this is my paragraph.'); 
   
// Add the node to the dom 
$newnode = $dom->appendChild($node); 
   
// Set the attribute 
$newnode->setAttributeNS("my_namespace", "id", "my_value"); 
  
echo $dom->saveXML(); 
?>输出:您可以按Ctrl + U查看DOM。

范例2:
<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
   
// Create an element 
$node = $dom->createElementNS("my_namespace", "x:p", 
                     'Hello, this is my paragraph.'); 
   
// Add the node to the dom 
$newnode = $dom->appendChild($node); 
  
echo "Before the addition of attributes:<br>"; 
   
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
   
// Set the attribute with a namespace 
$newnode->setAttributeNS("my_namespace", "style", "color:blue"); 
  
echo "<br>After the addition of attributes:<br>"; 
    
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
?>输出:
Before the addition of attributes: No of attributes => 0 After the addition of attributes: No of attributes => 1
参考: https://www.php.net/manual/en/domelement.setattributens.php
相关用法
- PHP DOMElement getAttributeNodeNS()用法及代码示例
 - PHP DOMElement removeAttributeNS()用法及代码示例
 - PHP DOMElement __construct()用法及代码示例
 - PHP DOMElement removeAttribute()用法及代码示例
 - PHP DOMElement getAttributeNS()用法及代码示例
 - PHP DOMElement getElementsByTagName()用法及代码示例
 - PHP DOMElement getAttributeNode()用法及代码示例
 - PHP DOMElement getAttribute()用法及代码示例
 - PHP DOMElement hasAttributeNS()用法及代码示例
 - PHP cos( )用法及代码示例
 - PHP Ds\Map get()用法及代码示例
 - PHP pos()用法及代码示例
 
注:本文由纯净天空筛选整理自gurrrung大神的英文原创作品 PHP | DOMElement setAttributeNS() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
