php調用twitter api

今天做了一個關於調用twitter api來同步twitter信息到自己網站的功能,雖然是比較簡單的功能,着實花費了我不少時間。網上有很多關於twitter api調用的方法,我試了幾個都沒有成功,貌似需要Oauth驗證,這個跟微信開發類似,需要token驗證。後來看到下面這篇博客解決了,講的挺詳細的。

主要步驟是:

第一步:到https://dev.twitter.com/apps/網站上創建一個app,獲取驗證需要的Consumer key, Consumer secret, Access token, Access token secret這四個參數。

第二步:引入twitteroauth進行驗證,這個twitteroauth可以到github上下載,源碼都是有的。最後按照給出的php代碼運行,調用get或post方法抓取,這裏是用到的是curl,twitteroauth裏封裝了http這樣一個方法,裏面用curl進行抓取。

Step 1 – Setup a Twitter Application

This process is straightforward and you should have a set of keys within a few minutes.

  1. Visit https://dev.twitter.com/apps/ and sign in using your Twitter username and password. This doesn’t have to be the username or password of the stream you need access to, just a Twitter account you control.

  2. Select ‘Create new application’ and enter the application details.

    1. The name and description can be anything you like really, but you can’t use ‘Twitter’ in the name.

    2. The website field can be your main website and doesn’t have to be the site where your Twitter feed or feeds are located.

    3. Callback URL can be left blank


  3. Enter the CAPTCHA info and click create

  4. On the next details screen, click ‘create my access token’. You may need to refresh the page after a few seconds if it doesn’t appear automatically.

  5. Make a note of the Consumer key, Consumer secret, Access token and Access token secret as highlighted below.


wKiom1NmCEHyakF1AAOc8x4MNy0704.jpg

Once you have an app setup within Twitter, this can be used for multiple user timelines on multiple websites – you do not need to setup one app per Twitter account or user timeline. Rate limits are set to 180 requests per 15 minute window however, per access token.

Step 2 – Authenticate the Twitter Feed

First off, head over to https://github.com/abraham/twitteroauth and download all the files. You’re only going to need to use a handful of these for this basic authentication but you might as well download the whole library. A key advantage of doing all this in PHP and recommended by Twitter is that your access tokens and keys are sent server side and not visible to the client.

Next, create a new php file, e.g. get-tweets1.1.php and use the following PHP code, substituting the 4 keys, twitter username and number of tweets you want to display. Upload this file along with the twitteroauth library to a folder on your web server and test the get tweets file.


Once you have an app setup within Twitter, this can be used for multiple user timelines on multiple websites – you do not need to setup one app per Twitter account or user timeline. Rate limits are set to 180 requests per 15 minute window however, per access token.


The PHP:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser= "twitterusername";
$notweets= 30;
$consumerkey= "12345";
$consumersecret= "123456789";
$accesstoken= "123456789";
$accesstokensecret= "12345";
functiongetConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
$connection= newTwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return$connection;
}
$connection= getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets= $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
echojson_encode($tweets);
?>

Hooray! you should have the latest tweets displaying in .json format. There should be a load of information displayed for each tweet within an array of information – it might look like a random mess but this is what you can now use to create a custom styled feed.

Check out my jQuery article if you want to create a custom twitter feed or my fading tweets post if you want to animate tweets one at a time. If you want to create a custom twitter search instead of a user timeline feed, see my Twitter search tutorial

You could of course get tweets to output direct from PHP as HTML but .json format and the articles above should be useful for anyone migrating from API V1 JavaScript Twitter feeds.

The above authentication code can also be easily modified for different Twitter endpoints, such as retrieving favorite tweets.

Troubleshooting tip 1: If you are getting internal 500 server errors on the twitter feed, this could be down to a number of things. Try enabling friendly PHP display errors or checking log files to see the exact error message. The most common mistake is an incorrect path to the twitteroauth.php file. Depending how the library is unzipped, it’s likely that the path will be “twitteroauth/twitteroauth/twitteroauth.php” or “twitteroauth/twitteroauth.php”. Use a relative path and not an absolute path, relative to where you put your get tweets file

Troubleshooting tip 2: Make sure you have cURL enabled on your server setup which is required by the Twitter OAuth library

Troubleshooting tip 3: If you’re getting a blank page, again, make sure you’re using a relative path to the OAuth library and ensure you have no HTML outside the opening and closing PHP

Troubleshooting tip 4: If you’re seeing a ‘null’ response, check the $connection->get call. I’ve seen null errors occur when trying to migrate old V1 calls that include a ‘callback’ parameter.

‘null’ responses when trying to authenticate Twitter also appear when using an earlier version of PHP – version 5.2.x. Try upgrading to a more recent version of PHP if possible or check your php.ini file and remove ‘curl_exec’ from ‘disable_functions’ if it exists. (thanks to Daniel Iftimie for this last one)

Troubleshooting tip 5: If the only thing you see is the get(); line and viewing page source shows the entire PHP, this means PHP isn’t activated on your server and your get tweets script isn’t being executed.

Note: The new rate limits for V1.1 for user timelines are 180 requests per 15 minute window. IP Address based limited no longer applies as it did with non-authenticated requests. So if you have a high volume of visitors to your website, or want to use the same access tokens across multiple sites and different twitter feeds then it’s probably worth setting up scheduled caching of tweets.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章