Twtter Streaming API(filter)を使ったサンプルプログラム

TwitterのStreaming APIの1つのfilterを試しに作ってみた。サンプルは、「iPad」という単語を含むつぶやきを垂れ流し続けます。

$ cat stream_filter.php
<?php

define('ID', '自分のTwitterアカウントのscreen_nameに置き換えて下さい');
define('PW', '自分のTwitterアカウントのpasswordに置き換えて下さい');
define('BASIC_AUTH', base64_encode(ID.':'.PW));
define('STREAM_FILTER', 'http://stream.twitter.com/1/statuses/filter.json');

$ctx = stream_context_create(
	array(
		'http' => array(
			'method' => 'POST',
			'header' => "Authorization: Basic " . BASIC_AUTH . "\r\n" .
			            "Content-type: application/x-www-form-urlencoded\r\n",	
			'content' => http_build_query(array('track' => 'iPad'))
		)
	)
);
$stream = fopen(STREAM_FILTER, 'r', false, $ctx);
while ($json = fgets($stream)) {
	$tweet = json_decode($json, true);
	if (!array_key_exists('text', $tweet)) continue;
        echo $tweet['user']['screen_name'] . '(' . $tweet['user']['name'] . "):\n";
        echo $tweet['text'] . "\n";
        echo "\ttweeted at " . date('Y/m/d H:i:s', strtotime($tweet['created_at'])) . "\n";
        echo "-------------------------------------------------------------------------\n";
}
fclose($stream);

PHP 5.2.0以降、もしくはPECL Jsonがインストールされてある必要があります。(あとエラー処理はやってないです)