2

サイトのソースを読み込もうとすると、次のようになることがあります (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);

これは今私を困惑させています...

4

2 に答える 2

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;
于 2012-08-14T14:36:38.737 に答える
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);
于 2012-08-14T12:34:02.607 に答える