Pages

Monday, April 20, 2009

How to Use the Arc90 PHP API to Get Info From Twitter

I recently decided, as a programmer and self-proclaimed web developer, to dive into the Twitter API, mostly just for fun.  From the main Twitter API Page you can access a series of prebuilt libraries for various programming languages, which provide wrappers around the main Twitter API.  With PHP being my web developing language of choice, I quickly glanced over the libraries available, with one clearly standing out: Arc90.  Not only is it maintained by a fellow "Matt," it also provides access to mostly anything you could think of in the world of Twitter.  By the end of this article, you should be able to pull all of your followers from Twitter and list some basic data about them.

Installation and Environment: The main page for Arc90 provides a very basic introduction on how to install and use the package, which is sufficient for getting your PHP environment ready to use.  So, for the purpose of this, I will assume that your PHP environment is all set, your includes are in order and cURL is ready to go.  If you need further help with any of those areas, feel free to leave a comment below.  So, I will assume you have a set up like the following:

  1. <?php  
  2.   
  3. require_once('Arc90/Service/Twitter.php');  
  4.   
  5. $twitter = new Arc90_Service_Twitter('username''password');  
  6.   
  7. try  
  8. {   
  9.     // Gets the users following you, response in JSON format  
  10.     $response = $twitter->getFollowers();  
  11.   
  12.     // Store the JSON response  
  13.     $theData = $response->getData();
  14.   
  15.     // If Twitter returned an error (401, 503, etc), print status code  
  16.     if($response->isError())  
  17.     {  
  18.         echo $response->http_code . "\n";  
  19.     }  
  20. }  
  21. catch(Arc90_Service_Twitter_Exception $e)  
  22. {  
  23.     // Print the exception message (invalid parameter, etc)  
  24.     print $e->getMessage();  
  25. }  

  26. ?>
Note a few changes: Obviously, on line 5 you will need to replace 'username' and 'password' with your login credentials.  On line 10, I went ahead and removed the parameter to request an XML response.  I saw that the default was JSON and wanted to try that (since that is another new technology for me).  I'm also using the getFollowers() API call instead.  On line 13, I'm storing the returned data for future use. 

Important Note Regarding API Rate Limits: If you are unfamiliar with Twitter and its associated API calls, you need to make sure that you don't overdo it on the number calls you make.  By default, Twitter allows you to have 100 API calls per hour (this includes using third party applications like TweetDeck or Nambu), so you'll need to keep an eye on how many calls you're using.  If you go over that limit, you can potentially be blacklisted -- which makes no one happy.  You have a couple of options: 1) Request to be whitelisted using this form.  This will allow you to use 20,000 requests per hour, or 2) Watch your rate limit using a built-in API method which monitors your status, and conveniently does not cost you an API call to use.  You can find more info regarding limits, whitelisting and blacklisting here.  Also, during development, I've gone and saved the output to a particular API call to a text document that I can parse while I test.  It doesn't provide real-time data, but it allows me to work on it as many times as I want without a single API call.

Using the Data: Now that we have our data response in JSON format to work with, let's get to it! To make good use of the data returned, I chose to put it in an associative array for organized access.  To do this, we use the json_decode method built into PHP as follows:
$dataArray = json_decode($theData, true);
To view an example of the kind of data that a getFollowers API call will return, we can view this method page in the documentation.  Also, for a detailed description of each key that can possibly be returned from any of the various API calls, you'll want to keep the complete list handy.  I ended up making a spreadsheet with the various API calls that I tested along with the associated return values, for a quick reference -- so you may want to do the same.

Let's say that we just want to loop through our followers (or at least the first 100) and print out some data about each one, line by line.  All we have to do is iterate through the array, pulling out the data we want and display it.  I stuck with a basic HTML table for this, but all you CSS gurus out there can have way more fun with this.  This assumes that you already have your associative data array, dataArray, ready to go:
  1. <html>
  2.         <head>
  3.             <title>Test</title>
  4.         </head>
  5.         <body>
  6.             <h1>Followers</h1>
  7.            <table border="1">
  8.                 <tr>
  9.                     <td>Image</td>
  10.                     <td>Screen Name</td>
  11.                     <td>Name</td>
  12.                     <td>Description</td>
  13.                     <td>URL</td>
  14.                     <td>Location</td>
  15.                     <td>Following</td>
  16.                     <td>Followers</td>
  17.                     <td>Status</td>
  18.                     <td>Status Count</td>
  19.                 </tr>
  20. <?php
  21.     $numItems = count($dataArray);
  22.     for($i = 0; $i < $numItems; $i++){
  23.         $currentItem = $dataArray[$i];
  24.        
  25.         $screenName = $currentItem["screen_name"];
  26.         $description = $currentItem["description"];
  27.         $followersCount = $currentItem["followers_count"];
  28.         $url = $currentItem["url"];
  29.         $name = $currentItem["name"];
  30.         $status = "";
  31.         if(isset($currentItem["status"]))
  32.         {
  33.             $status = $currentItem["status"]["text"];
  34.         }
  35.         $friendsCount = $currentItem["friends_count"];
  36.         $profileImage = $currentItem["profile_image_url"];
  37.         $location = $currentItem["location"];
  38.         $statusCount = $currentItem["statuses_count"];
  39.          echo "<tr><td><a href='http://www.twitter.com/".$screenName."'><img height='48' width='48' src='".$profileImage."'></a></td><td>".$screenName."</td><td>".$name."</td><td>".$description."</td><td>".$url."</td><td>".$location."</td><td>".$friendsCount."</td><td>".$followersCount."</td><td>".$status."</td><td>".$statusCount."</td></tr>";
  40.     }
  41. ?>
  42.     </table>
  43. </body>
  44. </html>
 You should end up with something that looks like:

If you have any trouble working through this, or have any questions, just let me know!

4 comments:

Bob I. said...

Nice job & thank you. Arc90 is a solid Twitter client, but I needed help getting from a returned XML or JSON object to usable data via PHP. Your tutorial really helped. It's basically plug & play. Thanks!

Matt Augustine said...

Hi Bob!
Thanks for stopping by. I'm glad that this was helpful for you. The more people diving into API's the better :)

Anonymous said...

Hi Matt, Thanks. I am new to the twitter api and I am noticing that whether I use your example code or the api json output like friends.json I am not getting back a complete list. I have an account with around 203 friends but the api only returns around 44 of them. Do you know what is causing that?
Thanks!
-J

Matt Augustine said...

Hi J,
I'm glad you're looking into using the Twitter API! The more developers building great tools, the better.

To answer your question, I believe by default the function that retrieves your friends retrieves the first 50 (I think it calls it the first "page"). And then you can use the same function, with different parameters, to pull the second page (next 50) and so on, if that makes sense.

Hopefully that helps!