如何使用PHP dom设置元素的ID?
问题描述:
我想设置一个元素的ID.我正在使用php dom.我不明白后续的工作原理.
I want to set id of an element. I'm using php dom. I could not understand how following will work.
DOMElement::setIdAttribute ( string $name , bool $isId )
我在手册中找到的唯一描述是- 将属性名称声明为ID类型.
The only description I found for this in manual is - Declares the attribute name to be of type ID.
我该怎么做?
答
如果要向HTML元素添加id属性,使其看起来像<p id="frob">...
,则不要使用setIdAttribute()
-它声明该属性$name
可以用作该元素的唯一标识符-作为id
属性的替代/添加.像这样使用setAttribute()
:
If you want to add an id attribute to your html element so that it looks like <p id="frob">...
you dont use setIdAttribute()
- it declares that the attribute $name
can be used as an unique identifier for that element - as an alternative/addition of the id
attribute. Use setAttribute()
like so:
$dom = new DOMDocument();
$dom->loadHTML('<html><body><p>FROB</p></body></html>');
$dom->getElementsByTagName('p')->item(0)->setAttribute('id', 'XXX');
print $dom->saveHTML();