twitter 建立基於網站的app 實時獲取tweets

1 必須得有一個twitter帳戶 php

2 建立一個基於自身網站的app(後期可用到其餘網站)
   https://dev.twitter.com/apps
   若是隻是但願獲取tweets就能夠不用填寫callback url了 json

3 建立bearer token,參考網頁:https://dev.twitter.com/docs/auth/application-only-auth api

4 根據key和secret建立一組base64加密數據,具體php這樣實現 數組

echo base64_encode( $key . ':' . $secret );

5 經過post請求獲取bearer token app

// 生成header
$auth = base64_encode( $key . ':' . $secret );
$headers = array(
	'Authorization: Basic ' . $auth
);

$ch = curl_init();

// 鏈接
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/oauth2/token');

// 發送post
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('grant_type' => 'client_credentials'));

// 發送header
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_exec($ch);
curl_close($ch);

頁面會輸入一組 bearer token curl

6 根據剛獲得的token獲取本身的tweets,php代碼以下,並記得修改其中的$screen_name爲你本身的: post

$headers = array(
	'Authorization: Bearer ' . $access_token
);
$ch = curl_init();

// 鏈接
curl_setopt($ch, CURLOPT_URL, 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' . $screen_name . '&count=10');

// 發送header
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// 不直接輸出數據,而是返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);

// 返回的json數據在$content裏,再轉換成對象或者數組到$data裏
$data = json_decode($content);

7 有可能你會常常修改你的screen_name,那麼能夠從上面代碼裏輸入的獲得的user_id來修改你的api_url爲:
   https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=*****&count=10 網站

相關文章
相關標籤/搜索