php xml setattribute,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()函数:

程序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.

c63cfa3ebec1acd0c6f4c47cce04925a.png

程序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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值