PHP file_get_contents在较大文件上返回504

时间:2016-04-05 00:52:53

标签: php file-get-contents

我正在构建一个从MySociety的EveryPolitician下载JSON文件的PHP网站。其中一些文件很小,而另一些则非常庞大。以下是我正在提出的典型请求的两个示例:

$g = file_get_contents("https://cdn.rawgit.com/everypolitician/everypolitician-data/65c4534/data/US_Virgin_Islands/Legislature/ep-popolo-v1.0.json");

$g = file_get_contents("https://cdn.rawgit.com/everypolitician/everypolitician-data/65c4534/data/UK/Commons/ep-popolo-v1.0.json");

第一行工作正常,我认为是因为请求的文件规模较小,但第二行在浏览器中永远加载,然后返回Gateway Timeout错误(504)。

如果我将浏览器指向第二个URL,它会很好地加载(虽然几秒钟之后;毕竟它非常大)。目前,该脚本正在我的本地计算机上运行,​​因此带宽或Internet速度没有差异。如您所见,这两个文件都来自GitHub。

让我更加困惑的是,第二行确实在几天前确实有效。

这只是PHP的file_get_contents()的限制吗?有没有什么方法可以使用file_get_contents()来解决它,还是有另一个库可以在这种情况下更好地工作?

1 个答案:

答案 0 :(得分:1)

您可以尝试设置默认套接字超时:

ini_set('default_socket_timeout', 360);

这将使file_get_contents()在6分钟内尝试连接。另外,你可以创建一个上下文数组并将它传递给file_get_contents()函数,这样就可以使你不必更改ini值ala:

$context = stream_context_create(array( 
    'http' => array( 
        'timeout' => 360 
        ) 
    ) 
);
file_get_contents("https://cdn.rawgit.com/everypolitician/everypolitician-data/65c4534/data/UK/Commons/ep-popolo-v1.0.json", 0, $context); 

希望这有帮助