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.

















0 Responses to “A [in]complete guide to use the Twitter API using PHP”