的file_get_contents抛出400错误请求错误PHP

问题描述:

我只是用file_get_contents()摆脱这样的用户的最新微博:的file_get_contents抛出400错误请求错误PHP

$tweet = json_decode(file_get_contents('http://api.twitter.com/1/statuses/user_timeline/User.json')); 

这工作在我的本地正常,但当我把它上传到我的服务器时,它引发此错误:

Warning: file_get_contents(http://api.twitter.com/1/statuses/user_timeline/User.json) [function.file-get-contents]:failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request...

不知道什么可能导致它,也许一个PHP配置我需要我的服务器上设置?

在此先感谢!

+0

阅读:http://stackoverflow.com/questions/697472/file-get-contents-returning-failed-to-open-stream-http-request-failed –

+2

请参见[这堆问题] [1],因为它可能会回答你的问题。 [1]:http://stackoverflow.com/questions/3710147/php-get-content-of-http-400-response –

+0

感谢彼得·布鲁克斯!这工作! – javiervd

您可能想尝试使用curl来检索数据而不是file_get_contents。卷曲有错误处理的更好的支持:

// make request 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://api.twitter.com/1/statuses/user_timeline/User.json"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 

// convert response 
$output = json_decode($output); 

// handle error; error output 
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { 

    var_dump($output); 
} 

curl_close($ch); 

这可能会给你一个更好的主意,为什么你收到的错误。常见的错误是达到服务器上的速率限制。

+1

你应该打印'curl_error($ ch)'以获得更详细的错误。 –

只是本答的一个小附录。 根据PHP manual,当使用curl_init()初始化cURL句柄时,可以设置CURLOPT_URL选项。

// make request 
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline/User.json"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 

// convert response 
$output = json_decode($output); 

// handle error; error output 
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) { 

    var_dump($output); 
} 

curl_close($ch); 

您可以使用file_get_contents添加ignore_errors选项设置为true,这样你会得到响应的整个身体在发生错误的情况下(HTTP/1.1 400为例),而不是只有一个简单的false

这里你可以看到一个例子:https://stackoverflow.com/a/11479968/3926617

如果你想获得响应的头部,你可以请求之后使用$http_response_header

http://php.net/manual/en/reserved.variables.httpresponseheader.php