使用php DOMDocument

时间:2016-11-18 20:48:48

标签: php domdocument

如何使用php DOMDocument将HTML属性添加到现有DOMElement?

如果我使用DOMElement::setAttribute()并将值保留为空,如

$node->setAttribute('my-property', '');

它总是导致空属性<span my-property="">...</span> 而不是不动产<span my-property>...</span>

1 个答案:

答案 0 :(得分:2)

您可以使用DOMElement::setAttributeNode将属性添加到现有DOMElement。

如果$node是DOMDocument $dom的DOMElement,您可以编写

$domAttr = $dom->createAttribute('my-property');
$node->setAttributeNode($domAttr);

这将导致<span my-property>...</span>