2

How can I add content to the newly created tag? For example, I need to create like the following tag:

<script src="https://stackoverflow.com/">
    alert("ok");
</script>

I have implemented the following code:

$finalDom = new DOMDocument;
$finalDom->loadHTML("", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);


$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");

$finalDom->appendChild($newElement);

The result of this code is an only empty script tag:

<script src="https://stackoverflow.com/"></script>
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
  • You can reference to this example as well : https://stackoverflow.com/questions/4400980/how-to-insert-html-to-php-domnode – codediesel Mar 25 '21 at 10:21
  • Look into you request, I think someone already asked before : https://stackoverflow.com/questions/4400980/how-to-insert-html-to-php-domnode – codediesel Mar 25 '21 at 10:23

3 Answers3

2

you can use createTextNode to add text node for the element, as

....
$newElement->setAttribute("src", "https://stackoverflow.com/");
$finalDom->appendChild($newElement);
$newElement->appendChild($finalDom->createTextNode('your text here'));
....
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

You can set the content using $textContent property of DOMElement.

$newElement = $finalDom->createElement("script");
$newElement->setAttribute("src", "https://stackoverflow.com/");

$newElement->textContent = 'alert("ok");';
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
-1

You can use any of these three options for adding text

elem.append(document.createTextNode(text))
elem.innerHTML = text
elem.textContent = text
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49