Twitter APIでTwitter Trendsを取得しよう
PHPでのTwitterトレンドを取得する例です。まずcomposerをインストールしましょう。
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
composerからTwitter OAuthライブラリをインストールします。
composer require abraham/twitteroauth
それではPHPスクリプトを書いていきましょう。アプリのディベロッパー登録はすませている前提で書いています。TwitterトレンドのAPIはロケーションに関するIDが必須なので、今回は東京(1118370)を指定しました。
<?php
require "vendor/autoload.php";
use AbrahamTwitterOAuthTwitterOAuth;
// Consumer key
$consumer_key = "**************";
// Consumer secret
$consumer_secret = "****************";
// Access token
$access_token = "*******************";
// Access token secret
$access_token_secret = "*******************";
// トレンドを取得する
$connection = new TwitterOAuth($consumer_key,$consumer_secret,$access_token,$access_token_secret);
$request = $connection->OAuthRequest("https://api.twitter.com/1.1/trends/place.json","GET",array("id"=>"1118370"));
$json = json_decode($request,true);
これでTwitterトレンドのデータは取得できました。あとはこれを必要に応じて配列に直したり、HTMLにしたりすると良いでしょう。
JSONにはツイート数が取れるものと取れないものがあるんだけど、この違いは何だろう…。