file_get_contents抛出400 Bad Request错误PHP

Jav*_*eva 26 php json file-get-contents

我只是用a file_get_contents()来获取像这样的用户的最新推文:

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

这在我的localhost上工作正常但是当我将它上传到我的服务器时它会抛出此错误:

警告: file_get_contents(http://api.twitter.com/1/statuses/user_timeline/User.json)[function.file-get-contents]:无法打开流:HTTP请求失败!HTTP/1.0 400错误请求...

不确定是什么导致它,也许我需要在我的服务器上设置php配置?

提前致谢!

Ben*_*owe 29

您可能希望尝试使用curl来检索数据而不是file_get_contents.curl更好地支持错误处理:

// 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);
Run Code Online (Sandbox Code Playgroud)

这可能会让您更好地了解收到错误的原因.常见错误是达到服务器的速率限制.


Wan*_*ber 7

您可以使用file_get_contentsignore_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