ツイート検索結果をリスト表示するコードを書いたよ 新TwitterAPI1.1版

DSC_8046

TwitterAPIのバージョンは1.0から1.1に変更になっていたことを忘れていました。TwitterAPI1.0は2013.4.12段階では動いていましたが、いつ停止してもおかしくない状況です。

ツイート検索結果をリスト表示しているサービスがあったので、コードをTwitterAPI1.1で書き直しました。言語はPHPです。

スポンサーリンク

コード

こんな感じのコードを書きました。

$keyword、$consumerKey、$consumerSecret、$accessToken、$accessTokenSecretの設定が必要です。

[php]
require_once ‘twitteroauth/twitteroauth.php’;
require_once ‘Cache/Lite.php’;

//config
$keyword = "";//検索キーワード
$consumerKey = "";
$consumerSecret = "";
$accessToken = "";
$accessTokenSecret = "";

$count= 10;//データ取得件数(MAX 100)
$lifetime = 00;//キャッシュ時間(秒)

//キャッシュ
$options = array(‘cacheDir’ => ‘dytw_cached/’,’caching’ => true,’lifeTime’ => $lifetime, ‘automaticCleaningFactor’ => ‘100’);
$cache_id=’dy’.rawurlencode($keyword);
$data_cache = new Cache_Lite($options);
$string=$data_cache->get($cache_id);

//データ取得
if(!$string){

$connection = new TwitterOAuth($consumerKey,$consumerSecret,$accessToken,$accessTokenSecret);
$string = $connection->OAuthRequest(‘https://api.twitter.com/1.1/search/tweets.json’, ‘GET’, array("q"=>rawurlencode($keyword),"result_type"=>"recent", "count"=>$count));
$data_cache->save($string,$cache_id);
}

//echo $string;

$obj = json_decode($string);

//var_dump($obj);

//データ生成
$str_contents = "";

if ($obj->statuses) {

foreach ($obj->statuses as $statuses) {

//タイムスタンプ
$time = strtotime($statuses->created_at);
$time = date("Y年m月j日 H時i分",$time);

$text = htmlspecialchars(str_replace(array("rn","r","n"), ”, $statuses->text));

$rt_text = ‘RT @’.$statuses->text;
$rt_link = ‘ <a href="javascript:void(0)" onclick="document.location=’http://twitter.com/home?status=’+encodeURI(”.$rt_text.”)">RT</a>’;
$re_text = ‘@’.$statuses->from_user;

$text = auto_link($text);

$re_link = ‘ <a href="javascript:void(0)" onclick="document.location=’http://twitter.com/home?status=’+encodeURI(”.$re_text.”)+’&in_reply_to_status_id=’+encodeURI(”.$statuses->id_str.”)">Re</a>’;

$str_contents .= "<p><a href="http://twitter.com/{$statuses->from_user}" target="_blank"><img src="{$statuses->user->profile_image_url}" width="48" height="48" alt="{$statuses->user->screen_name}" class="twimg"></a> <a href="http://twitter.com/{$statuses->user->screen_name}" target="_blank">@{$statuses->user->screen_name}</a> [{$time}] {$rt_link} {$re_link}</p>";

$str_contents .= "<p style=’border-bottom:2px solid #dddddd;padding-bottom:10px;margin-bottom:25px’>{$statuses->text}</p>";

}

} else {

$str_contents = "";
}

if($str_contents){
$str_contents = ‘<div id="twiform" style="border:solid #cccccc 2px;padding:20px;margin:10px 0">’.$str_contents.'</div>’;
}

function auto_link ($text) {
return preg_replace(‘/([^="’>]|^)(https?|ftp)(://[-_.!~*'()a-zA-Z0-9;/?:@&amp;=+$,%#]+)/’, ‘$1<a href="$2$3" target="_blank">$2$3</a>’, $text);
}

echo $str_contents;

?>[/php]

ポイント

・Auth認証が必要

1.1から全てのデータ取得にAuth認証が必要になりました。コード内に記述するキーとトークンは、Twitterのアプリケーション開発ページから取得する必要があります。

そして、PHP認証ライブラリ「twitteroauth」が必要です。

方法は小粋空間さんの記事が分かりやすいです。

・取得回数に制限

今回利用するGET search/tweetsは15分間に180回までリクエストできます。1分間に12回、5秒に1回リクエストです。5秒間キャッシュをすれば良いですが、設定は余裕をみて、60秒にしておきました。

その他の制限については、REST API v1.1 Limits per window by resourceを参照してください。

・GET search/tweetsのパラメータが変更

GET search/tweetsでは、取得件数は最大100件まで。pageのパラメータ設定ができなくなっていますので、ご注意ください。指定できるパラメータについては、GET search/tweetsを参照してください。

ご参考にどうぞ!

PHPtwitter
スポンサーリンク
当ブログの記事に共感していただけたら、また読みに来ていただけると嬉しいです。読んでくれる方の数が多くなると、更新するヤル気に繋がります(^^)
フォロー、ブックマークしていただけると、ブログ更新を見逃しません
わかったブログ

コメント

タイトルとURLをコピーしました