PHP file_get_contents不适用于某些URL

时间:2014-10-29 13:11:19

标签: php web-scraping

为什么PHP的file_get_contents不适用于某些网址?

<?php
    $html = file_get_contents('http://modagram.com');
?>

上面我收到了这个警告:

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

1 个答案:

答案 0 :(得分:1)

像@MarkBaker在评论中所说,网络服务器可能阻止了未知的UserAgents,试图伪造一个:

$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