Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Simple HTML DOM Parser adding script tag

Is it possible using PHP Simple HTML DOM Parser to add a new script taga inside the head of a simple_html_dom object that has a full html from a home page?

i need to add some nodes inside that template, one of this nodes is a script tag with jquery and the other is a div with some text that i am pulling from my database.

i previously did something like this: (with DOMDocument )

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($remote);
$head = $dom->getElementsByTagName('head')->item(0);
$jquery = '$(document).ready(function(){ $("#feed_home").hide()});
  if (window.location.hash) {
    Destino = window.location.hash.replace(\'#!\', \'?\');

         window.location.href = window.location.href.split(\'#\')[0] + Destino;
}
';

$script = $dom->createElement('script', $jquery);
$script_type = $dom->createAttribute('type');

$script_type->value = 'application/javascript';
$script->appendChild($script_type);
$head->appendChild($script);
like image 501
Fo Nko Avatar asked Dec 16 '22 12:12

Fo Nko


2 Answers

PHP Simple HTML DOM allows manipulation:

$html = str_get_html($rawhtml);
$inject  = '<script type="text/javascript">alert("Hello")</script>';
$html->find('head', 0)->innertext = $inject.$html->find('head', 0)->innertext;
echo $html;

http://simplehtmldom.sourceforge.net/manual.htm#frag_access_tips

like image 99
Pyry Liukas Avatar answered Dec 18 '22 02:12

Pyry Liukas


No, simple html dom doesn't do dom manipulation. With phpquery though you can do:

$doc->find('head')->append('<script src="foo"></script>');
like image 38
pguardiario Avatar answered Dec 18 '22 01:12

pguardiario