2015-12-30 27 views
1

要获取body标签中的内容,我使用下面的代码。如何在没有javascript代码的情况下获得正文内容

$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>

+2

已经问: http://stackoverflow.com/questions/7130867/remove-script-tag-from-html-content – nullexception

回答

0

解决方案here已解决我的问题。下面完全的代码删除脚本标记和身体标记及其内容:

$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; 
2

试试这个:

$html = preg_replace("/<script.*?\/script>/s", "", $html); 

在做正则表达式的事情可能出错,所以它的安全这样做:

$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html; 

所以当“事故”发生时,我们得到原始的$html而不是空字符串。

+0

这只删除脚本标记,但保留javascript内容。这个想法是删除脚本标记和JavaScript内容。 – Lomse

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是这样的任务噩梦

相关问题