Subscribe

RSS Feed (xml)

HOWTO : TWEETS FROM PHP

Many of our readers have been asking how they can access to twitter from PHP code and here we come with a simple tutorial that will give all the basics to do even more complex operations.

Let’s see in this simple tutorial how we can read our timeline and update our status from a simple piece of PHP code.

First of all we suggest you to have a look at the Twitter API wiki where you can have access to many useful information about the API and how to use them in different coding languages.

We will use for this example one of the many available open source libraries written to use twitter from PHP called PHP Twitter written by Tijs Verkoyen, you can download the library 1.0.2 version from here .

We will notice that PHP Twitter class has no real documentation and the only way to have some information is to read the Twitter Wiki API pages and understanding how API works just look into the PHP Twitter code for the corresponding function to call.

The first step to do is to include the PHP Twitter library into our code, so if we place the twitter.php file into the same directory of our project file we will write something like:

Now we need to create a Twitter class object and give it two parameters that are the twitter ID and password to log into twitter API with our identity.

We are at this point authenticated into twitter api system so we can start with our requests, and the first thing we will do is to update our status using the updateStatus() function this way:

The content of the $user_text string should be written into your twitter status now, yes it’s just that simple :)

Another useful PHP Twitter library function is the getFriendsTimeline() that you can use to retrieve the 20 most recent statuses posted by you and your friends, actually this is like looking at the /home twitter page once logged into twitter.

This function returns an Array with all 20 statuses and additional information, we will use the print_r() function to read out the server response:

You can obviously go through the array and have a look for example at who was the last one to tweet and what he said:



02
03 include "twitter.php";
04
05 $twi_user = new Twitter("username","password");
06
07 $aTimeline = $twi_user->getFriendsTimeline();
08
09 echo $aTimeline[0]['user']['screen_name']." was the last to tweet and said : \n".$aTimeline[0]['text']."\n\n";
10

Note that this last example was intended to be used with commandline php, if you want to print the result on a web page just replace each ‘\n’ with a ‘
’.

Well this simple tutorial ends here and we hope to have given you some basic and useful ideas on how you can interact with twitter using some simple PHP code that you can use in your websites in different ways.

Related Posts with Thumbnails