2014-04-23 199 views
2

使用PHP我試圖抓取一個網頁,然後自動抓取圖像。PHP 500內部服務器錯誤file_get_contents

我已經試過如下:

<?php 
$url = "http://www.domain.co.uk/news/local-news"; 

$str = file_get_contents($url); 
?> 

<?php 
    $opts = array('http'=>array('header' => "User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1\r\n")); 
    $context = stream_context_create($opts); 
    $header = file_get_contents('http://www.domain.co.uk/news/local-news',false,$context); 
?> 

<?php 
include('simple_html_dom.php'); 

$html = file_get_html('http://www.domain.co.uk/news/local-news'); 

$result = $html->find('section article img', 0)->outertext; 
?> 

但這些都返回與Internal Server Error。我可以在瀏覽器中完美地查看網站,但是當我嘗試在PHP中抓取頁面時,它會失敗。

有什麼我可以嘗試嗎?

+1

[啓用錯誤報告](http://blog.flowl.info/2013/enable-display-php-errors/) – DanFromGermany

+0

[PHP文件\ _get \ _contents 500內部服務器錯誤](http:/ /stackoverflow.com/questions/10524748/php-file-get-contents-500-internal-server-error) – majidarif

回答

2

請嘗試下面的代碼:它會將內容保存在本地文件中。

<?php 
$ch = curl_init("http://www.domain.co.uk/news/local-news"); 
$fp = fopen("localfile.html", "w"); 
curl_setopt($ch, CURLOPT_FILE, $fp); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_exec($ch); 
curl_close($ch); 
fclose($fp); 
?> 

現在您可以準備localfile.html。

+0

這會成功創建一個文件,但是當我嘗試通過在代碼中添加以下內容來訪問它時,它將覆蓋本地文件.html並返回500錯誤 'include('simple_html_dom.php'); $ html = file_get_html('http://domain.com/build/wp-content/plugins/news-plugin/localfile.html'); $ result = $ html-> find('lead-story',0) - > outertext; echo $ result;' – ngplayground

+0

對我來說工作正常..檢查你的代碼.. –

1

有時您可能會在file_get_contents打開http URL時發生錯誤。 即使您已在php.ini中

設置allow_url_fopen = On對我來說,解決辦法是還設立「USER_AGENT」的東西。

+0

更好:使用cUrl。許多主機阻止使用file_get_contents。 –