Monthly Archives: March 2009

Write a twitter application in PHP

I have been addicted to twitter, so much that (in recent days) there hasn’t been a day when I have stayed away from twitter [Except for one day, when a friend of mine challenged me to stay away & yes, I won it! But that friend is yet to do what he was supposed to do after losing.].

I also have been using the twitter API to write simple twitter apps at appb.in. Felt like, sharing some gyaan on how to write a twitter app in PHP:purpose of this post. Target audience: a n00b or a beginner. Here we start…

 

First, If you haven’t gone through the  Twitter API wiki,  skim through it. You will get an idea about what we are interacting with. Keep it handy.  

Have PHP manual open for reference. [I have the .chm version of the manual open whenever I do some coding.]

To receive (or send) any info from(to) twitter, you will have to do a POST  or GET  request to twitter. There are different URL’s(methods) for different operations as mentioned in the API documentation. Based upon the application that you are developing, you will use appropriate API methods.

These methods return XML, JSON,  RSS and Atom depending upon the request that you send (http://twitter.com/statuses/public_timeline.format here  format can be xml or json, etc.,) . I generally use  XML, but have also used JSON. PHP has functions that help you easily read these formats, so no worries. Next task is to parse it & interpret the information. Then we need to do the processing as per the applications needs.

Then comes the last but the most challenging part, presenting the information to the user. AJAXy stuff are popular these days, so learn a little bit of jQuery( because there isn’t any other easy way of ajaxyfying that I know of) if you want. I’m not dealing with AJAX here, so let’s keep it aside. You can easily present the information in a HTML page with some neat stying using css.

 

Now, let us go through a simple app called commontweeps, which lets you find common friends between two people.  This is non-AJAXy and uses XML format.

From the API documentation, to get a list of friends, the URL that we need to use is “http://twitter.com/statuses/friends/username.xml”.  You now need to query twitter for the info. We can do that with a simple function,

 
function getfilecontents($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
$res=curl_exec($ch);
$info=curl_getinfo($ch);
curl_close($ch);
if($res === false || $info['http_code'] !=200 ) { $ret=array(false,$info['http_code'],$res);}
else{$ret=array(true,$info['http_code'],$res);}
return $ret;
}

 It is a function that uses cURL to fetch data from the url being passed to it. This works without replacing the ‘username:password’ (with your username and password) but considering that twitter API has rate limiting, you can get your username whitelisted (i.e, if you are planning to release an app for friends/public).

Next is, how to use this function. Let us write a small piece of code, just to look at the response from twitter and how we can use it. 

http://wg.vinayraikar.com/apps/commontweeps/asktwitter.php.txt  This script will read, parse the xml and show results like this.

Now, I guess we are clear with the querying-twitter part. Next, we need to do some processing to get our desired results. 

Twitter returns only 100 friends per call, so if  someone has more than 100 friends then you should query more than once with a page  parameter in the url. We will do that in our application with a while loop until no more ‘user’s are returned. The code goes something like this…

$xml[$page] = new SimpleXMLElement($fi[2]);
$user1count=0;
while(isset($xml[$page]->user[0])){
      foreach ($xml[$page]->user as $user) {
         $userdet[(string)$user->screen_name]=array( 'screen_name'=> (string)$user->screen_name, 'location'=>(string)$user->location, 'description'=>(string)$user-> description, 'profile_image_url'=> (string)$user-> profile_image_url, 'url'=>(string)$user-> url, 'name'=>(string)$user->name );
         $user1details[$user1count]= (string)$user->screen_name;
         $user1count++;
       } 
      $page++;
      $fi=getfilecontents($friendsurl.$username1.'.xml?page='.$page);
      if($fi[0]===false){
           echo "Error : ".$fi[1];
           $err=new SimpleXMLElement($fi[2]);
           echo " ".$err->error."";
           // echo "";
           die();
      }
   $xml[$page] = new SimpleXMLElement($fi[2]);
}

This piece of code is doing two things,

One: Collecting userdetails in an array $userdet with the username as the key.

Two: Collecting the friends name in an array $user1details .

At the end of the loop, $user1details will have a list of all the followers & $userdet will have all the follower details.

 

We need to do this for two users and get their friends list. Say, $user1details and $user2details are the arrays for two users, then all you need to get common tweeps is use the array_intersect function:

$commonfriends=array_intersect($user1details, $user2details);

Now, $commonfriends will have a list of all common friends. [You can do much more magic with different ideas by using other array functions like array_diff, array_merge.]

Next is presentation, the most crucial and difficult task.  Let’s keep is simple, displaying an unordered list with this piece of code…

$commoncount=count($commonfriends);
if(is_array($commonfriends)){
echo "<p>You have $commoncount friends in common.</p>";
echo "<ul id='commonlist'>";
foreach($commonfriends as $friend){
echo "<li>";
echo "<span class='nl'><img class='img' src='".$userdet[$friend]['profile_image_url']."'></img><br/>";
echo "<a class='screen-name' href='".$userdet[$friend]['screen_name']."'>".$userdet[$friend]['screen_name']."</a></span>";
echo "<span class='nr'> <p class='desc'> ".$userdet[$friend]['description']." | <a href='".$userdet[$friend]['url']."' title='".$userdet[$friend]['url']."'>web</a> </p></span>";
echo "</li>";
}
echo "</ul>";
}
else{echo "<p>No common Tweeps!</p>";}
}

You can now do some styling using CSS to give it a nice look.

Well, we are done with it, just that we didn’t talk about how to get the input from the user. We need to present a form to the user and then get his input. I hope, you will get it from the final working code.

So, our final commontweeps code is here. The code is more like an procedural hack, lacking proper error handling, cacheing & stuff but it’s one of our first steps right?

Based upon the application idea, you will have to use different API methods and request types (GET or POST) as per the API documentation.

There are PHP libraries for twitter like this one by arc90 that will ease your task. 

OK. That’s it!   Hope I  have been clear and not confusing {let me know in the comments, there’s always scope for improvement  :D}.  You can also catch me on twitter as @vsr  .  Happy tweeting!!

What do you believe in..

There was a time, when I was all careless, carefree. Never did I care about philosophy or life. I accepted things, as they came, did what I wanted ( which was usually what people around me did ).

And then, I met a few people. These people were different, their thoughts, beliefs, customs, traditions & language. Never before had I met people with such beliefs. Their beliefs were strong.  I was in no way uncomfortable, because there wasn’t a time when I was strongly attached to any belief system. It was a new learning experience.

And then there was a time, I wanted to classify myself, chose a philosophy, a theist or an atheist or something else. With no proof, I couldn’t choose. So, I had to be agnostic. But, I was not satisfied. I wanted to have an opinion,a strong one. I wanted to stick to something. And then, I watched ‘The Big Lebowski‘  and ‘The Fight Club‘ .  A new word got into my vocabulary: ‘Nihilism‘.

That was the time, I needed a pillar, to cling. And looking at people and events around me, Nihilism was the way to go. “Screw the world!”, I said without giving it a deep thought.

But then, I thought a little. Nihilism sounded cool but that wasn’t the practical way to live. I chucked it out. I wanted to go back to my old ways of carefree living.

There is so much to learn about life  that one life isn’t enough. There have been thousands of philosophers, scientists who have dedicated their lives to find answers to mystery of life. And I don’t think anybody has found an answer yet.

So, now… Do I stick to one belief system and criticize every other?  May be I won’t. I will try to accept things as they come. I will try to be open to other people’s belief.   There will be times when real life experiences will force me to think one belief system is much closer to truth than the other. Life’s going to be a nice learning experience. I will choose good things, things that suit me and make my own philosophy, my own belief system, one that will grow with me.

Anyway,I like this dialogue very much…

Mere man ko bhaya, mein kuththa kaat ke khaya.

So, what do you believe in?