A [in]complete guide to use the Twitter API using PHP
This article is complete n00b's guide to using Twitter API via PHP. Currently this article only covers the Timeline Methods with PHP scripts.
This article is an [in]complete n00b’s guide to using Twitter API via PHP using a PHP Library wrapper created by Justin Poliey.
Twitter uses the REST API (Representational State Transfer). Here you make a request to the API url with the options and it returns you the result either in XML,JSON formats. We will be using PHP’s cURL functions to help us make requests to the Twitter API and get the results in the form of XML so we can easily traverse through each node.
This guide covers the first part of Twitter API, the timeline methods. You would require a lil bit of PHP knowledge to get this running.
Remember, Twitter returns the result either in XML format or in JSON format.
You can virtually retrieve everything using the Twitter API. Along with this guide, please keep the http://apiwiki.twitter.com/Twitter-API-Documentation open too.
What areas does this guide cover ?
- Initialization (Setup the PHP Library and Login to your Twitter account)
- How to retrieve last 20 tweets ?
- How to retrieve list of Followers ?
- How to retrieve last 20 tweets posted by your friends?
- How to retrieve mentions ? (i.e tweets made to @username)
- JSON OR XML Results ?
Requirements
-
PHP Twitter API Library by Justin Poliey
You need a PHP class using the Twitter API. We will be using the one created by Justin Poliey (http://github.com/jdp/twitterlibphp/tree/master). Download it and save it as
twitter.lib.php
How to use it ?
Before you start, first you need to include the above PHP class in your PHP file/application. Since it is a class, you also need to create an object of the above class viz twitter.
1. Initialization
You need to include only one instance of the initialization code in your php file. Do include it before any php code. This function requires you to put in your Twitter username and password. Thus you are authenticated to Twitter and can use all the API’s Twitter has to provide. Remember you can make a maximum of 150 API calls in an hour.
<?php
#INITIALIZATION CODE. There has to be one instance of this code in the top of your php file.
# Load twitter class.
require_once ('twitter.lib.php');
#create object of twitter class by providing your username and password
$t= new twitter("your twitter username", "your twitter password");
/**
* Adds a link href to links if any in the input tweet.
* @param string $tweet Your Tweet
* @return string
*/
function returnTweet($tweet) {
return ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $tweet);
}
?>
The following functions can only be used by an authenticated user. The following functions can retrieve results of other Twitter users as well.
2. How to retrieve your last 20 tweets ?
This function will allow you to retrieve the latest tweets of any Twitter User. Only an authenticated user can invoke this function and can retrieve any Twitter user’s tweets unless the account you requested is a protected user timeline. By default it is 20 tweets are returned.
API used : statuses/user_timeline
Syntax : getUserTimeline ([array $options = array()], [string $format = 'xml'])
Parameter 1 = $options
(if no options are given by default will retrieve your latest tweets)
idOptional. Specifies the ID or screen name of the user for whom to return the user_timeline.user_idOptional. Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name.screen_nameOptional. Specfies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID.since_idOptional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.max_idReturns only statuses with an ID less than (that is, older than) or equal to the specified ID.countOptional. Specifies the number of statuses to retrieve. May not be greater than 200.pageOptional. Specifies the page to retrieve.
Example: $options = array("screen_name" => "Twitter user's screen name (can be yours or any other)", "count" => 20);
Parameter 2 = $format
- xml (default)
- json
Response : Please check statuses/user_timeline too see what all responses are returned.
By default, the results are returned in XML format, so we need to use PHP’s SimpleXMLElement to create an object of the XML.
PHP Code :
<?php
#don`t forget the initialization code. There has to be one instance of the initialization code before using the following code
# Gets the last 20 tweets posted by you
$options = array("screen_name" => "twitter screen name", "count" => 20);
$mystatus = new SimpleXMLElement($t->getUserTimeline($options));
/*
//If you want to retrieve results in JSON format
$mystatus = json_decode($t->getUserTimeline($options,"json"));
*/
//shows the last 20 Tweets by you
echo '<ol>';
foreach($mystatus as $s) {
$status_msg = $s->text; //you can retrieve any response using $s->
//for example you can retrieve the date of this message by echoing $s->created_at
echo '<li>' . returnTweet($status_msg) . '</li>';
}
echo '</ol>';
?>
3. How to retrieve of Followers ?
This function retrieves all the followers (a maximum of 100 at a time). Only an authenticated user can invoke this function. You can retrieve any Twitter User’s followers.
API used : statuses/followers
Syntax : getFollowers ([array $options = array()], [string $format = 'xml'])
Parameter 1 = $options
(if no options are given by default will retrieve your list of followers)
idOptional. Specifies the ID or screen name of the user for whom to return the user_timeline.user_idOptional. Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name.screen_nameOptional. Specfies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID.pageOptional. Specifies the page to retrieve.
Example: $options = array("screen_name" => "Twitter user's screen name (can be yours or any other)", "count" => 20);
Parameter 2 = $format
- xml (default)
- json
Response : Please check statuses/followers too see what all responses are returned.
By default, the results are returned in XML format, so we need to use PHP’s SimpleXMLElement to create an object of the XML.
PHP Code :
<?php
#don`t forget the initialization code. There has to be one instance of the initialization code before using the following code
$options = array("screen_name" => "twitter screen name", "page" => 1);
# Get all followers of the user (maximum 100 at a time)
$followers = new SimpleXMLElement($t->getFollowers($options));
//shows your followers
echo '<ol>';
foreach($followers as $f) {
$follower_screen_name = $f->screen_name; //follower screen name
$follower_latest_status_msg = $f->status->text; //follower latest statys message
echo '<li><strong>'. $follower_screen_name . '</strong> ' . returnTweet($follower_latest_status_msg) . '</li>';
}
echo '</ol>';
?>
The following functions ONLY display results of the authenticated user and cannot be used to display results of other Twitter users without their authentication.
4. How to retrieve last 20 tweets by your friends ?
This function will allow you to retrieve a particular user’s friend’s tweets. (i.e from the ones the user follows). Only an authenticated user can invoke this function and can only retrieve the authenticated user’s friend’s tweets. By default 20 tweets are retrieved.
API used : statuses/friends_timeline
Syntax : getFriendsTimeline ([array $options = array()], [string $format = 'xml'])
Parameter 1 = $options
(if no options are given by default will retrieve your friend’s statuses)
since_idOptional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID.max_idReturns only statuses with an ID less than (that is, older than) or equal to the specified ID.countOptional. Specifies the number of statuses to retrieve. May not be greater than 200.pageOptional. Specifies the page to retrieve.
Example: $options = array("screen_name" => "your screen name", "count" => 20);
Parameter 2 = $format
- xml (default)
- json
Response : Please check statuses/friends_timeline too see what all responses are returned.
By default, the results are returned in XML format, so we need to use PHP’s SimpleXMLElement to create an object of the XML.
PHP Code :
<?php
#don`t forget the initialization code. There has to be one instance of the initialization code before using the following code
# Gets the last 20 tweets posted by you
$options = array( "count" => 20);
# Gets the last 20 tweets of your friends
$allstatus = new SimpleXMLElement($t->getFriendsTimeline($options));
//shows the last 20 tweets
echo '<ol>';
foreach($allstatus as $p) {
$friends_tweet = $p->text;
$friends_screen_name = $p->user->screen_name;
echo '<li>' . returnTweet($friends_tweet) . ' (' . $friends_screen_name . ')</li>';
}
echo '</ol>';
?>
5. How to retrieve mentions ? (i.e tweets made to @username)
This function retrieves all the mentions (i.e tweets made to @username ). Only an authenticated user can invoke this function and can only retrieve the authenticated user’s mentions.
API used : statuses/mentions
Syntax : getMentions([array $options = array()], [string $format = 'xml'])
Parameter 1 = $options
(if no options are given by default will retrieve your list of mentions)
idOptional. Specifies the ID or screen name of the user for whom to return the user_timeline.user_idOptional. Specfies the ID of the user for whom to return the user_timeline. Helpful for disambiguating when a valid user ID is also a valid screen name.screen_nameOptional. Specfies the screen name of the user for whom to return the user_timeline. Helpful for disambiguating when a valid screen name is also a user ID.pageOptional. Specifies the page to retrieve.
Example: $options = array("screen_name" => "your screen name", "count" => 20);
Parameter 2 = $format
- xml (default)
- json
Response : Please check sstatuses/mentions too see what all responses are returned.
By default, the results are returned in XML format, so we need to use PHP’s SimpleXMLElement to create an object of the XML.
PHP Code :
<?php
#don`t forget the initialization code. There has to be one instance of the initialization code before using the following code
# Get all followers of the user (maximum 100 at a time)
$mentions = new SimpleXMLElement($t->getMentions());
//shows your followers echo '<ol>';
foreach($mentions as $m) {
$mentioner_screen_name = $m->user->screen_name; //mentioner screen name
$msg = $m->text; //follower latest statys message //text
echo '<li><strong>'. $mentioner_screen_name . '</strong> ' . returnTweet($msg) . '</li>';
}
echo '</ol>';
?>
JSON OR XML
You can parse results either in JSON or XML. Currently the above code, parse results which are XML, if you were to retrieve em in JSON, then the only change will be,
Example :
Processes XML
$mentions = new SimpleXMLElement($t->getMentions());
Processes JSON
$mentions = json_decode($t->getMentions("","json"));
This has to applied to every API call where you want JSON data to be returned.
Conclusion
Well that was just Part 1 of this guide. Part 2 will cover how to use the API to post tweets and using Twitter for authentication.
















I am often to running a blog and i actually appreciate your content. The article has really peaks my interest. I’m going to bookmark your site and keep checking for brand spanking new information.
F*ckin’ tremendous things here. I am very happy to see your post. Thanks so much and i’m having a look forward to touch you. Will you kindly drop me a mail?
I like the valuable info you provide for your articles. I’ll bookmark your blog and check once more here regularly. I’m somewhat sure I’ll learn plenty of new stuff right here! Good luck for the next!
A powerful share, I simply given this onto a colleague who was doing a little bit similar evaluation on this. He actually bought me breakfast because I found it for him.. smile.
Pretty great post. I simply stumbled upon your weblog and wanted to mention that I have truly loved surfing around your weblog posts. After all I?ll be subscribing to your rss feed and I am hoping you write once more soon!
Heya i’m for the primary time here. I found this board and I find It truly helpful & it helped me out much. I am hoping to provide something back and aid others such as you aided me.
hi, it’s pucka until finally create internet sites with search engines like a function many thanks because the fraction which you’ve given. frequently, i’m really astonished, however and many others.
Thanks , I’ve recently been looking for info about this topic for ages and yours is the greatest I have discovered so far. But, what about the conclusion? Are you positive concerning the supply?
I wish you Merry Christmas and a happy new year, and further development of the blog.
Hey there, Thank you for that great article! Regards, 500 rublei
I’m still learning from you, but I’m improving myself. I definitely love studying the whole lot that’s written in your blog.Keep the stories coming. I beloved it!
Hi! I know this is kind of off-topic but I had to ask. Does managing a well-established website such as yours require a large amount of work? I am brand new to blogging however I do write in my diary every day. I’d like to start a blog so I can share my personal experience and views online. Please let me know if you have any suggestions or tips for new aspiring blog owners. Appreciate it!
Once I originally commented I clicked the -Notify me when new feedback are added- checkbox and now every time a remark is added I get 4 emails with the same comment. Is there any manner you can take away me from that service? Thanks!
advertising
Hey there just wanted to give you a quick heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same results.
I was focusing on creating quality content on a regular basis but this sounds like a good idea, build then drive traffic, simple as that.
I have had that same thing happen. Check out mytownsaves.com
Yeah bookmaking this wasn’t a bad determination great post!
Great beat ! I would like to apprentice while you amend your site, how can i subscribe for a blog website? The account aided me a acceptable deal. I have been tiny bit acquainted of this your broadcast offered vibrant clear idea
Good site! I truly love how it is simple on my eyes and the data are well written. I am wondering how I might be notified whenever a new post has been made. I have subscribed to your RSS feed which must do the trick! Have a nice day!
Aloha!
Some really nice stuff on this site, I enjoy it.
An appealing conversation is worth comment. I believe that you must write read more about this subject, may well become a taboo subject matter although generally people are too few to communicate on these kinds of subjects. Thank you. ! . !
After researching a few of the weblog posts in your website now, and I actually like your means of blogging. I bookmarked it to my bookmark web site record and will probably be checking back soon. Pls check out my web site as nicely and let me know what you think.
Tina, As always very wise advice to develop a successful internet marketing strategy. Thank you very much
Great info and straight to the point. I don’t know if this is in fact the best place to ask but do you people have any ideea where to hire some professional writers? Thank you
If you did not get the synchronization-rights for Only Time, then Sony, for whom I believe Enya records, has every right to pull the song. And the RIAA and MPAA are not going to give you any breaks if they catch wind of it. Its all about the money.Doom and Gloom. God, how the world sucks it up! Floods, Tsunamis, earthquakes, war, volcanos, famine, firestorms, hurricanes, typhoons, chaos, human suffering, mans inhumanity to man? Business as usual folks.
Great stuff! this would too useful to me as a designer. thanks for sharing
is it possible to get mention done only by my followers ?
Immediately following the release of her first collection of dates in the United kingdom uk, Britney has achieved unparalleled interest for tickets. She is likely to be performing 21 of her smash hits which include 2 surprise tracks
Pretty good job. I just came across your blog and wanted to say I really enjoyed reading your posts. Anyway I'll be subscribing to your feed and I hope you post soon..
I do not know if others also have such an impression but this article is great.
Thanks Michael
Only problem is you've left out the cursor parameter when retrieving the followers list. And that's what I'm a bit stuck on at the moment. Thanks anyway, apart from that, good article!
wow thats some intense php, i think i'll stick with a wordpress plugin now that its 2010 and wp3.0 is bad ace
Its such as you learn my thoughts! You appear to know a lot approximately this, like you wrote the guide in it or something. I think that you simply can do with a few % to force the message house a little bit, however instead of that, this is great blog. A great read. I will definitely be back.
Thanks for some other informative site. The place else could I am getting that type of info written in such a perfect means? I’ve a undertaking that I’m simply now operating on, and I have been at the glance out for such info.
advertising
Aloha!
I have to voice my appreciation for your kind-heartedness for individuals that require assistance with this important concept. Your special commitment to getting the solution all through ended up being incredibly functional and has empowered some individuals much like me to get to their targets. The helpful report implies much to me and still more to my office colleagues. Many thanks; from all of us.
Appreciate it for this terrific post, I am glad I discovered this internet site on yahoo.
Sorry for your enormous review, but I’m genuinely loving the newest Zune, and hope this, in addition as the superb critiques some other men and women have written, will assist you come to a decision if it is really the best option for you.
I will immediately take hold of your rss as I can’t to find your email subscription hyperlink or newsletter service. Do you’ve any? Kindly let me recognise in order that I could subscribe. Thanks.
I would like to get across my gratitude for your kindness for persons who absolutely need help with that subject. Your real commitment to getting the message across had been wonderfully functional and has continuously permitted people much like me to achieve their desired goals. Your amazing interesting publication entails this much to me and even further to my office colleagues. Thanks a lot; from everyone of us.
Hello!
http://dmmsdnjfgjherjrttyu.com dmmsdnjfgjherjrttyu
dmmsdnjfgjherjrttyu
dmmsdnjfgjherjrttyu