Home > Mobile >  insert custom script file into <head> tag in php file obtained with file_get_contents()
insert custom script file into <head> tag in php file obtained with file_get_contents()

Time:07-23

I would like to be able to modify elements in a DOM that I actually obtained using php function file_get_contents(). My way to go is actually try to insert a script tag into the but I'm getting:

Fatal error: Uncaught Error: Call to undefined method DOMElement::parent()

That's my code:

$html=str_get_html(file_get_contents('http://www.elpais.com/'));
foreach($html->find('head') as $header) {
        $document = new DOMDocument();
        $element = $document->createElement('script');
        $script = $document->createTextNode('console.log("new custom script added!");');
        $element->appendChild($script);
        $header->appendChild($element);
        echo $document->saveHTML($document->childNodes[0]);
}

If anyone would now why appendChild on $header is not working or a better way to do it, I would be very grateful for the help. Thanks!

CodePudding user response:

I actually found the way to do it here:

Adding javascript to html file loaded by file_get_contents in php

Now I'm trying to call a script file, instead of injecting a function inside the tag, with no success. Anyone knows a way to do it?

CodePudding user response:

Do you mean run a specific file?if so, add a file in your script

<script type="text/javascript" src="ur_file.js"></script>
  • Related