Twitter Streaming APIをPHPから使うMEMO

ここからphirehoseを落としてくる

サンプルプログラムをコピーし、以下のphpプログラムを作成する

<?php
require_once('lib/UserstreamPhirehose.php');

// The OAuth credentials you received when registering your app at Twitter
define("TWITTER_CONSUMER_KEY", "ここにコンシューマーキーを記入");
define("TWITTER_CONSUMER_SECRET", "ここにシークレットキーを記入");


// The OAuth data for the twitter account
define("OAUTH_TOKEN", "ここにOAUTHトークンを記入");
define("OAUTH_SECRET", "ここにOAUTHシークレットキーを記入");

mb_language("ja");
mb_internal_encoding('UTF-8');

/**
 * Example of using Phirehose to display a live filtered stream using track words
 */
class FilterTrackConsumer extends OauthPhirehose
{
  /**
   * Enqueue each status
   *
   * @param string $status
   */
  public function enqueueStatus($status)
  {
    /*
     * In this simple example, we will just display to STDOUT rather than enqueue.
     * NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being
     *       enqueued and processed asyncronously from the collection process.
     */
    $data = json_decode($status, true);
    if (is_array($data) && isset($data['user']['screen_name'])) {
      if ($data['lang']==="ja") {
        if (!array_key_exists('retweeted_status', $data)) {
          $tweet=str_replace("\n","",urldecode($data['text']));
          print $data['created_at'] . "'\t@" 
              . mb_convert_encoding($data['user']['screen_name'],"sjis-win","UTF-8") . " ("
              . mb_convert_encoding($data['user']['name'],"sjis-win","UTF-8") . ")\t"
              . mb_convert_encoding($tweet,"sjis-win","UTF-8") . "\n";
          var_dump($data["user"]);
        }
      }
    }
  }
}

class SampleConsumer extends OauthPhirehose
{
  public function enqueueStatus($status)
  {
    $data = json_decode($status, true);
    //if (is_array($data) && isset($data['user']['screen_name'])) {
    //  print $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n";
    // }
    if (is_array($data) && isset($data['user']['screen_name'])) {
      if ($data['lang']==="ja") {
        if (!array_key_exists('retweeted_status', $data)) {
          $tweet=str_replace("\n","",urldecode($data['text']));
          print $data['created_at'] . "'\t@" 
              . mb_convert_encoding($data['user']['screen_name'],"sjis-win","UTF-8") . " ("
              . mb_convert_encoding($data['user']['name'],"sjis-win","UTF-8") . ")\t"
              . mb_convert_encoding($tweet,"sjis-win","UTF-8") . "\n";
        }
      }
    }
  }
}



//キーワードで絞り込んで表示
$sc = new FilterTrackConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);
$sc->setTrack(array('#艦これ','E-1','E-2','E-3','E-4','E-5','E-6','E-7'));             //検索する文字列をセット

//全体からTL表示
//$sc = new SampleConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_SAMPLE);


$sc->setLang('ja');          // 日本語のTweetのみ
$sc->consume();              // Start streaming



とりあえず指定キーワードを含んだTwitterのタイムラインを眺めたいという目的は達成。
キーワードで絞り込まず、全体のTLの一部を取得したい場合は$sc = new の部分のコメントアウトを逆に。

$data[‘user’]にはツイート情報が入っている。
項目は以下の通り、

var_dump($data['user']);

array(38) {
  'id'                      =>  int(123456789)
  'id_str'                  =>  string(9) "123456789"
  'name'                    =>  string(31) "ユーザー名"
  'screen_name'             =>  string(9) "username"
  'location'                =>  NULL
  'url'                     =>  string(123) "http://lil.la/"
  'description'             =>  string(123) "任意のユーザー説明"
  'protected'               =>  bool(false)
  'verified'                =>  bool(false)
  'followers_count'         =>  int(12345)
  'friends_count'           =>  int(12345)
  'listed_count'            =>  int(175)
  'favourites_count'        =>  int(18)
  'statuses_count'          =>  int(1234567)
  'created_at'              =>  string(30) "Tue Mar 15 10:42:20 +0000 2011"
  'utc_offset'              =>  int(32400)
  'time_zone'               =>  string(5) "Tokyo"
  'geo_enabled'             =>  bool(false)
  'lang'                    =>  string(2) "ja"
  'contributors_enabled'    =>  bool(false)
  'is_translator'                       =>  bool(false)
  'profile_background_color'            =>  string(6) "ABB8C2"
  'profile_background_image_url'        =>  string(48) "http://abs.twimg.com/images/themes/theme1/bg.png"
  'profile_background_image_url_https'  =>  string(49) "https://abs.twimg.com/images/themes/theme1/bg.png"
  'profile_background_tile'             =>  bool(false)
  'profile_link_color'              =>  string(6) "CB7218"
  'profile_sidebar_border_color'    =>  string(6) "EEEEEE"
  'profile_sidebar_fill_color'      =>  string(6) "EFEFEF"
  'profile_text_color'              =>  string(6) "333333"
  'profile_use_background_image'    =>  bool(false)
  'profile_image_url'               =>  string(74) "http://pbs.twimg.com/profile_images/1713831010/asuha2_400x400.jpg"
  'profile_image_url_https'         =>  string(75) "https://pbs.twimg.com/profile_images/1713831010/asuha2_400x400.jpg"
  'profile_banner_url'              =>  string(58) "https://pbs.twimg.com/profile_images/1713831010/asuha2_400x400.jpg"
  'default_profile'                 =>  bool(false)
  'default_profile_image'           =>  bool(false)
  'following'                       =>  NULL
  'follow_request_sent'             =>  NULL
  'notifications'                   =>  NULL
}

print $data[‘created_at’] ・・・の所を書き換えればDBに突っ込むとかいろいろできそう。

コメント

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