PHP file_get_contents 对某些 URL 不起作用 [英] PHP file_get_contents does not work for some URLs
本文介绍了PHP file_get_contents 对某些 URL 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 PHP 的 file_get_contents 对某些 URL 不起作用?
Why PHP's file_get_contents do not work for some URLs?
<?php
$html = file_get_contents('http://modagram.com');
?>
对于上述我收到此警告:
For above I receive this warning:
PHP Warning: file_get_contents(http://modagram.com): failed to open stream: HTTP request failed! in /var/www/html/scraping/test.php on line 2
推荐答案
就像@MarkBaker 在评论中所说的,webserver 可能正在阻止未知的 UserAgents,尝试伪造一个:
Like @MarkBaker said in the comment, webserver is probably blocking unknown UserAgents, try to fake one:
$context = stream_context_create([
'http' => [
'user_agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)',
],
]);
$html = file_get_contents('http://modagram.com', false, $context);
print_r($http_response_header); // see response headers
这篇关于PHP file_get_contents 对某些 URL 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文