[英]PHP DOMDocument: what is the nicest way to safely add text to an element
[英]How to add text node in new created element with PHP DOMDocument
如何向新創建的標簽添加內容? 例如,我需要創建如下標簽:
<script src="https://stackoverflow.com/">
alert("ok");
</script>
我已經實現了以下代碼:
$finalDom = new DOMDocument;
$finalDom->loadHTML("", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
此代碼的結果是一個唯一的空腳本標記:
<script src="https://stackoverflow.com/"></script>
您可以使用createTextNode為元素添加文本節點,如
....
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
$newElement->appendChild($finalDom->createTextNode('your text here'));
....
您可以使用DOMElement的$textContent屬性設置內容。
$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");
$newElement->textContent = 'alert("ok");';
您可以使用這三個選項中的任何一個來添加文本
elem.append(document.createTextNode(text))
elem.innerHTML = text
elem.textContent = text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.