使用file_get_contents获取DOM后在<head>插入自定义脚本报错求助
问题分析与解决方案
错误根源
你混用了Simple HTML DOM Parser和PHP原生DOM扩展两个不同的解析库:
str_get_html是Simple HTML DOM库的方法,返回的$header是该库的元素对象,而非原生DOMElement。- 你后续调用的
appendChild是原生DOM扩展的方法,Simple HTML DOM的元素对象并没有这个方法,因此触发Call to undefined method错误。
方案一:纯用Simple HTML DOM Parser实现
Simple HTML DOM有自己的API来修改元素内容,直接用它的属性操作即可:
// 确保已引入Simple HTML DOM Parser文件 // require 'simple_html_dom.php'; $html = str_get_html(file_get_contents('http://www.elpais.com/')); foreach($html->find('head') as $header) { // 构造script标签字符串,追加到head内部HTML末尾 $script = '<script>console.log("new custom script added!");</script>'; $header->innerHtml .= $script; // 输出修改后的完整HTML echo $html; }
方案二:纯用PHP原生DOM扩展实现(推荐,无需第三方依赖)
PHP内置DOM扩展功能更稳定,无需额外安装库,处理不规范HTML时也更可靠:
// 禁用HTML解析错误提示,避免目标页面不规范HTML触发报错 libxml_use_internal_errors(true); $htmlContent = file_get_contents('http://www.elpais.com/'); $dom = new DOMDocument(); $dom->loadHTML($htmlContent); $xpath = new DOMXPath($dom); // 定位所有head标签 $headNodes = $xpath->query('//head'); if ($headNodes->length > 0) { $head = $headNodes->item(0); // 创建script元素及文本内容 $script = $dom->createElement('script'); $scriptText = $dom->createTextNode('console.log("new custom script added!");'); $script->appendChild($scriptText); // 将script插入到head末尾 $head->appendChild($script); // 输出修改后的HTML echo $dom->saveHTML(); } // 清理解析错误缓存 libxml_clear_errors();
内容的提问来源于stack exchange,提问作者rojele
相关产品推荐
相关产品推荐

