📜  PHP | DOMElement setAttribute()函数

📅  最后修改于: 2022-05-13 01:56:25.433000             🧑  作者: Mango

PHP | DOMElement setAttribute()函数

DOMElement::setAttribute()函数是PHP中的一个内置函数,用于将具有给定名称的属性设置为给定值。如果该属性不存在,它将被创建。

句法:

DOMAttr DOMElement::setAttribute( string $name, string $value )

参数:该函数接受上面提到的两个参数,如下所述:

  • $name:它指定属性的名称。
  • $value:指定属性的值。

返回值:此函数在成功时返回 DOMAttr,在错误时返回 FALSE。

例外:如果节点是只读的,此函数会抛出 DOM_NO_MODIFICATION_ALLOWED_ERR。

下面给出的程序说明了PHP中的DOMElement::setAttribute()函数

方案一:

createElement("p",
     'Hello, this is my paragraph.');
  
// Add the node to the dom
$newnode = $dom->appendChild($node);
  
// Set the attribute
$newnode->setAttribute("style", "color:red");
  
echo $dom->saveXML();
?>

输出:


Hello, this is my paragraph.

方案二:

loadXML("

    
        

Geeksforgeeks

        

Second heading

    
");    // Get the elements $node = $dom->getElementsByTagName('h1')[0];     echo "Before the addition of attributes:
";    // Get the attribute count $attributeCount = $node->attributes->count(); echo 'No of attributes => ' . $attributeCount;     // Set the id attribute $node->setAttribute('new', 'value');     echo "
After the addition of attributes:
";     // Get the attribute count $attributeCount = $node->attributes->count(); echo 'No of attributes => ' . $attributeCount; ?>

输出:

Before the addition of attributes:
No of attributes => 1
After the addition of attributes:
No of attributes => 2

参考: https://www. PHP.net/manual/en/domelement.setattribute。 PHP