要获取正文标记中的内容,请使用以下代码。
$html = @file_get_contents($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('body');
$body = $nodes->item(0)->nodeValue;
如何从$ body中删除js代码?任何看起来像
的js代码 <script>
/*Some js code*/
</script>
答案 0 :(得分:2)
试试这个:
$html = preg_replace("/<script.*?\/script>/s", "", $html);
在进行正则表达式时,事情可能会出错,所以这样做会更安全:
$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;
因此,当“意外”发生时,我们会得到原始$html
而不是空字符串。
答案 1 :(得分:1)
如果您已经使用DOMDocument
,那么为什么不删除节点?!
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile("from_link_to.html");
$scripts = $dom->getElementsByTagName('script');
foreach ($scripts as $script) {
$scripts->removeChild($script);
}
...
仔细查看The DOMDocument class以及regular expression
噩梦的方式来完成此类任务。
答案 2 :(得分:0)
解决方案here解决了我的问题。下面的代码从body标签中完全删除了脚本标记及其内容:
$doc = new DOMDocument();
$doc->preserveWhiteSpace = false;
@$doc->loadHTML($html);
$script = $doc->getElementsByTagName('script');
$remove = [];
foreach ($script as $item) {
$remove[] = $item;
}
foreach ($remove as $item) {
$item->parentNode->removeChild($item);
}
$node = $doc->getElementsByTagName('body');
$body = $node->item(0)->nodeValue;
echo $body;