我使用以下代码从Twitter API检索一定数量的推文:
$cache_file = "cache/$username-twitter.cache";
$last = filemtime($cache_file);
$now = time();
$interval = $interval * 60; // ten minutes
// Check the cache file age
if ( !$last || (( $now - $last ) > $interval) ) {
// cache file doesn't exist, or is old, so refresh it
// Get the data from Twitter JSON API
//$json = @file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" . $username . "&count=" . $count, "rb");
$twitterHandle = fopen("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count", "rb");
$json = stream_get_contents($twitterHandle);
fclose($twitterHandle);
if($json) {
// Decode JSON into array
$data = json_decode($json, true);
$data = serialize($data);
// Store the data in a cache
$cacheHandle = fopen($cache_file, 'w');
fwrite($cacheHandle, $data);
fclose($cacheHandle);
}
}
// read from the cache file with either new data or the old cache
$tweets = @unserialize(file_get_contents($cache_file));
return $tweets;
Run Code Online (Sandbox Code Playgroud)
当然,$ username和fopen请求中的其他变量是正确的,它会生成正确的URL,因为我收到错误:
警告:fopen(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Schodemeiss&count=5)[function.fopen]:无法打开流:HTTP请求失败!第187行/home/ellexus1/public_html/settings.php中的HTTP/1.1 400错误请求
每当我尝试打开我的页面时,^^错误都会返回.
任何想法为什么会这样?我是否需要使用OAuth来获取我的推文!?我是否必须将我的网站注册为可能获得帖子的地方?
我真的不确定为什么会这样.我的主人是JustHost.com,但我不确定这是否会造成任何差异.欢迎所有想法!
谢谢.
安德鲁
PS.此代码位于一个函数中,其中正确传递了用户名,间隔和计数,因此在错误代码中它创建了一个格式良好的地址.
您可能会受到速率限制
400错误请求:请求无效.随附的错误消息将解释原因.这是在速率限制期间将返回的状态代码.
非认证呼叫每小时150个请求(基于IP地址)
经过身份验证的呼叫每小时350个请求(基于经过身份验证的用户呼叫)
您必须进行身份验证以避免弹出这些错误.
还请cURL在处理twitter时使用.我用过file_get_contents并fopen调用了twitter API,发现它非常不可靠.你会偶尔受到打击.
更换fopen用
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$it = curl_exec($ch); //content stored in $it
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5724 次 |
| 最近记录: |