實作讀取twitter內容的方式

今天有個需求, 是要讀取某 twitter 帳號的內容, 該帳號內容原本也就是公開的, 所以也就不用 follow 就可以讀取. 以下簡單介紹程式讀取的方式:

1. 先需要有個 twitter 帳號, 而已必須提供手機號碼並驗證
2. 到 https://apps.twitter.com/ 建立一個應用程式, 建立的時候也會通知你的帳號必須滿足上面 1. 的條件
3. 在建立好的應用程式中, 取得兩個重要的參數, key 與 secret (會在 Keys and Access Tokens 頁籤上)
4. 開始實作程式, 先參考這裡:
https://dev.twitter.com/oauth/reference/post/oauth2/token
https://dev.twitter.com/oauth/application-only
使用 oauth 取得 access token, 程式碼如下:

$key = "[your application key]";
$secret = "[your application secret]";
$access_token = "";

$b64 = base64_encode($key . ":" . $secret);

$url = 'https://api.twitter.com/oauth2/token';
$data = array('grant_type' => 'client_credentials');

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\nAuthorization: Basic " . $b64 . "\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) { 
    /* Handle error */ 
}else{
    $json = json_decode($result);
    $access_token = $json->{"access_token"};
}

5. 取到 access_token 後, 就可以利用這個 user_timeline API 進行取得對應帳號的 tweeter 內容:
https://dev.twitter.com/rest/reference/get/statuses/user_timeline
程式碼如下:

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=[筆數]&screen_name=[twitter account]";

$options = array(
    'http' => array(
        'header' => "Authorization: Bearer " . $access_token . "\r\n",
        'method' => "GET",
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) { 
    /* Handle error */ 
}else{
    $json = json_decode($result);
    for($i=0;$i<count($json);$i++){
        echo $json[$i]->{"text"} . "<br>";
    }
}

這樣就可以順利取得對應的 twitter 帳號發表的內容了.

這篇使用了 PHP5 不使用 curl 方式的程式內容, 參考這篇(CURL-less method with PHP5):
http://stackoverflow.com/questions/5647461/how-do-i-send-a-post-request-with-php