500 内部服务器错误 file_get_contents

问题描述 投票:0回答:3

如果我尝试阅读网站的源代码,有时会得到以下内容(显示示例 URL):

Warning: file_get_contents(http://www.iwantoneofthose.com/gift-novelty/golf-ball-finding-glasses/10602617.html)
[function.file-get-contents]: failed to open stream: HTTP request failed!
HTTP/1.1 500 Internal Server Error in /home/public_html/pages/scrape.html on line 165

但是 URL 本身是好的..为什么会发生这种情况?

我尝试了以下解决方法建议,但结果相同:

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$header = file_get_contents('https://www.example.com',false,$context);

这让我现在很困惑......

php web-scraping file-get-contents
3个回答
2
投票

问题出在您的 User-Agent 标头中。这对我有用:

$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.iwantoneofthose.com/gift-novelty/golf-ball-finding-glasses/10602617.html',false,$context);

2
投票

我不知道确切的原因,但在使用某些服务器时,

file_get_contents
失败了。但你还有一个选择;

$fp = fsockopen("www.iwantoneofthose.com", 80, $errn, $errs);
$out  = "GET /gift-novelty/golf-ball-finding-glasses/10602617.html HTTP/1.1\r\n";
$out .= "Host: www.iwantoneofthose.com\r\n";
$out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0\r\n";
$out .= "Connection: close\r\n";
$out .= "\r\n";
fwrite($fp, $out);

$response = "";
while ($line = fread($fp, 4096)) {
    $response .= $line;
} 
fclose($fp);


$response_body = substr($response, strpos($response, "\r\n\r\n") + 4);
// or
list($response_headers, $response_body) = explode("\r\n\r\n", $response, 2);

print $response_body;

0
投票

“500 内部服务器错误”通常表示服务器端在尝试满足请求时出现问题。如果您在使用 file_get_contents 函数时遇到此错误,通常意味着服务器无法检索指定的资源。

您可以采取以下几个步骤来解决此问题:

检查 URL:确保您尝试使用 file_get_contents 获取的 URL 正确且可访问。确保没有拼写错误,并且您尝试访问的资源可用。

© www.soinside.com 2019 - 2024. All rights reserved.