4

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);
Fo Nko
  • 620
  • 10
  • 22
  • 1
    Why did you change from DOM to simple_html_dom? (Partly just curious, but may also allow someone to suggest a third alternative...) – IMSoP Mar 28 '13 at 22:41
  • because its so easy to select whatever you need from a full template that you have loaded inside a simple_hteml_dom object, just by using the css selectos.. like jquery. DOMdocument is really hard to follow.. at least for me – Fo Nko Mar 28 '13 at 22:44
  • 2
    @FoNko in that case, you might like to consider the combination of the Symfony [CssSelector](http://symfony.com/doc/current/components/css_selector.html) and the [DomCrawler](http://symfony.com/doc/current/components/dom_crawler.html) libraries which allow you to do exactly that, but more powerful. – Adam Elsodaney Mar 28 '13 at 23:06
  • 1
    Or phpQuery, or [any of the libxml based packages Gordon mentions here](http://stackoverflow.com/a/3577662/358679). – Wrikken Mar 28 '13 at 23:16
  • great, i will check on that later today... thanks guys!! – Fo Nko Mar 28 '13 at 23:22

2 Answers2

11

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

Pyry Liukas
  • 431
  • 6
  • 10
1

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

$doc->find('head')->append('<script src="foo"></script>');
pguardiario
  • 53,827
  • 19
  • 119
  • 159