我只是使用file_get_contents()
来获取用户的最新tweet,如下所示:
$tweet = json_decode(file_get_contents('http://api.twitter.com/1/statuses/user_timeline/User.json'));
这在我的本地主机上工作得很好,但是当我将它上传到我的服务器时,它抛出了这个错误:
文件获取警告:文件获取()函数。-file_get_contents-file_get_contents:无法打开流: HTTP请求失败!HTTP/1.0 400错误请求...
不确定是什么原因导致的,也许是我需要在服务器上设置的php配置?
提前感谢!
发布于 2011-12-13 08:31:12
您可能希望尝试使用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);
这可能会让您更好地了解为什么会收到错误。一个常见的错误是达到服务器上的速率限制。
发布于 2016-07-08 05:35:16
您可以使用file_get_contents
将ignore_errors
选项集添加到true
,这样,在发生错误(例如,HTTP/1.1400)时,您将获得整个响应正文,而不仅仅是一个简单的false
。
您可以在这里看到一个示例:https://stackoverflow.com/a/11479968/3926617
如果你想访问响应的头部,你可以在请求之后使用$http_response_header
。
http://php.net/manual/en/reserved.variables.httpresponseheader.php
发布于 2016-01-17 15:43:51
只是对本的回答做了一点补充。根据PHP manual,可以在使用CURLOPT_URL ()初始化cURL句柄时设置curl_init选项。
// 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);
https://stackoverflow.com/questions/8482782
复制相似问题