簡體   English   中英

如何使用 PHP DOMDocument 在新創建的元素中添加文本節點

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM