Streaming APIメモ

statuses/sample

http://wiki.dobon.net/index.php?.NET%A5%D7%A5%ED%A5%B0%A5%E9%A5%DF%A5%F3%A5%B0%B8%A6%B5%E6%2F96

sample (以前 spritzer と呼ばれていたもの)
public な情報のうち、ある一定割合のものを取得する (firehose の精度の悪いバージョン。要するに、全てのデータが得られる保証はない。データ抜けがある可能性がある)
gardenhose 契約を結ぶことで、契約なしの場合より精度を上げることができる(が、firehose と比べるとはるかに精度は悪い)

<?php
ini_set("display_errors",1);
error_reporting(E_ALL|E_STRICT);

header("content-type:text/plain;charset=UTF-8");

//int
$cnt       = 1;
//str
$user      = ''; //TwitterのID
$password  = ''; //TwitterのPW
//array
$array     = array();
//resource
$stream    = fopen("http://{$user}:{$password}@stream.twitter.com/1/statuses/sample.json", "r");


while( $json = fgets($stream) )
{
    $array = json_decode($json, true);

    if( isset($array["user"]) )
    {
        print $cnt . "\n";
        print_r($array);
        print "\n\n\n";
    }

    if(100 < ++$cnt)
    {
        exit;
    }
}
print "ストリーミングのループから抜けました";

statuses/filter

http://wiki.dobon.net/index.php?.NET%A5%D7%A5%ED%A5%B0%A5%E9%A5%DF%A5%F3%A5%B0%B8%A6%B5%E6%2F97
http://weblet.jp/2010/10/twitter-streaming-%E3%82%92php%E3%81%A7%E3%82%BD%E3%82%B1%E3%83%83%E3%83%88%E3%81%A7%E4%B8%AD%E7%B6%99%E3%81%97%E3%81%A6%E3%81%BF%E3%81%9F%E3%80%82/

filter (以前 follow と呼ばれていたものと track と呼ばれていたものを統合)
1件以上のフィルターを設定し、絞り込んだ情報(public な情報に限定)を取得する

<?php
ini_set("display_errors",1);
error_reporting(E_ALL|E_STRICT);


//int
$cnt       = 1;
//str
$id        = ''; //TwitterのID
$pw        = ''; //TwitterのPW
$word      = ''; //検索ワード
//resource
$stream;
$ctx       = stream_context_create
(
    array
    (
        'http' => array
        (
            'method'        => 'POST',
            'header'        => "Authorization: Basic " . base64_encode($id . ':' .$pw) . "\r\n" .
            "Content-type: application/x-www-form-urlencoded\r\n",
            'content'        => http_build_query( array('track' => $word) )
        )
    )
);


header("content-type:text/plain;charset=UTF-8");
$stream = fopen('http://stream.twitter.com/1/statuses/filter.json', 'r', false, $ctx) or die("error");


while( $json = fgets($stream) )
{
    $tmp = json_decode($json,true);


    if( isset($tmp["user"]) )
    {
        print $cnt . "\n";
        print_r($tmp);
        print "\n\n\n\n\n\n\n\n\n\n\n";
        $cnt++;
    }

    if(100 < $cnt)
    {
        exit;
    }
}
print "ストリーミングのループから抜けました";