PHP Simple HTML DOM Parser添加脚本标记

时间:2013-03-28 22:37:25

标签: php domdocument simple-html-dom

是否可以使用PHP Simple HTML DOM Parser在一个simple_html_dom对象的头部添加一个新脚本taga,该对象具有来自主页的完整html?

我需要在该模板中添加一些节点,其中一个节点是带有jquery的脚本标签,另一个是带有一些文本的div,我从数据库中提取。

我之前做过类似的事情:(使用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);

2 个答案:

答案 0 :(得分:11)

PHP Simple HTML DOM允许操作:

$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

答案 1 :(得分:2)

不,简单的html dom不会做dom操作。有了phpquery,你可以这样做:

$doc->find('head')->append('<script src="foo"></script>');
相关问题