DOMElement::setAttribute()函数是PHP中的内置函数,用于将具有给定名称的属性设置为给定值。如果该属性不存在,则将创建它。
用法:
DOMAttr DOMElement::setAttribute( string $name, string $value )
参数:该函数接受上述和以下描述的两个参数:
$name:它指定属性的名称。
$value:它指定属性的值。
返回值:如果成功,此函数返回DOMAttr,如果错误则返回FALSE。
异常:如果节点是只读的,则此函数将抛出DOM_NO_MODIFICATION_ALLOWED_ERR。
下面给出的程序说明了PHP中的DOMElement::setAttribute()函数:
程序1:
// Create a new DOMDocument
$dom = new DOMDocument();
// Create an element
$node = $dom->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.
程序2:
// Create a new DOMDocument
$dom = new DOMDocument();
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
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