0

i want to write/inject a javascript code inside a html file "template.html".

<div id="scr">

</div>

and javascript is

<script>
    window.onload = function(){}
</script>

PHP

        $doc = new DOMDocument();

        $doc->loadHTMLFile("template.html");

        $doc->getElementById('scr')->nodeValue="<script>window.onload = function(){}</script>"; 

        $doc->saveHTMLFile("html/".$name.".html");

What i am getting is

<div id="scr">&lt;script&gt;window.onload = function(){}&lt;/script&gt;</div>

What i am expecting:

<div id="scr"><script>window.onload = function(){}</script></div>
Kaleem Nalband
  • 687
  • 7
  • 21
  • Have you tried using htmlentities() ? – nitnjain Feb 05 '20 at 07:44
  • 3
    Because I have not used this myself I don't want to give an answer, but from what I read on this it seems you want to append a child element to add a tag. It is quite obvious that nodeValue here treats the string as what to show on the page and therefor escapes the "<" and ">". I suspect you would want to use appendChild. See https://www.php.net/manual/en/domnode.appendchild.php – Virre Feb 05 '20 at 07:44
  • i tried the createChild and appendChild and this worked – Kaleem Nalband Feb 05 '20 at 07:54

2 Answers2

0
$doc = new DOMDocument();

        $doc->loadHTMLFile("template.html");

        $script=$doc->createElement("script");

        $script->nodeValue="window.onload = function(){}";

        $doc->getElementById('scr')->appendChild($script);

        $doc->saveHTMLFile("html/".$name.".html");
Kaleem Nalband
  • 687
  • 7
  • 21
0

I have create a method setInnerHTML

function setInnerHTML($element, $html)
{
    $fragment = $element->ownerDocument->createDocumentFragment();
    $fragment->appendXML($html);
    $clone = $element->cloneNode(); // Get element copy without children
    $clone->appendChild($fragment);
    $element->parentNode->replaceChild($clone, $element);
}

//your code

$doc = new DOMDocument();

$doc->loadHTMLFile("template.html");

setInnerHTML($doc->getElementById('scr'),"<script>window.onload = function(){}</script>"); 

$doc->saveHTMLFile("html/".$name.".html");

this will work like a charm and so generic to use too...

Ronak Dhoot
  • 2,322
  • 1
  • 12
  • 19