In this tutorial we will be creating a quick and simple Twitter Update Manager as well as a Client that will can be published on your website or blog displaying your latest tweets.
At the heart of this code, is a third-party Twitter API Client developed by Arc90. They have been gracious enough to allow the rest of us, to use of their Code library. You will want to first of all download this library to your system. You should also note, that this tutorial is not an OAuth tutorial. That may be covered in a later tutorial.
As you can see from the above screenshot, the small app we will be creating will display three of your latest tweets, as well as a form below the tweets that will allow you to update a new twitter message.
Download Code:
$>mkdir twitter-client $>cd twitter-client $>git clone git://github.com/dizzytree/PHP-Twitter-Client.git
NOTE: You can choose to Install GIT or you can download a zip/tar from the the GitHub site.
Here is the link to the direct download page.
Here is a link to install GIT on Mac OSX
Directory Structure
Before, we can start the actual coding, here is the directory structure will will need to create in order to proceed.

NOTE: Arc90_Service_Twitter requires PHP 5.1.4 or later and libcurl 7.10.5 or later. Also note that the source code includes a file called info.php which will allow you to view your version of PHP and if you have LIBCURL installed. Also important to note, I tried using the latest ver 2.2.3 and I could not get the api to work. I had to use 2.2.0. This version is included with the source code below.
Setup the config.php
<?php
/*
|---------------------------------------------------
| SAMPLE CONSTANT / CONFIG VARIABLES
|---------------------------------------------------
*/
define('TWITTER_USER', 'username');
define('TWITTER_PASS', 'password');
// Utility Function
// Reads in a Twitter Msg and returns properly formatted URLS and Hashes
function format_tweet($str)
{
// function code removed to save space.
// Refer to downloadable code
}
// Elapsed Time for query updates
function get_elapsedtime($time)
{
// function code removed to save space.
// Refer to downloadable code
}
There are only two constant variables that we will need to be concerned about;
- Your Twitter Username and
- Your Twitter Account Password.
Just replace these variables with your own, and you'll be all set to use the Twitter API.
Located within the config.php file are two utility functions. These functions are used for parsing your twitter feed as well as giving the twitter timestamp a more user friendly string. I removed the code for these function above to save some space.
Create the twitter.php File
<?php
// Set the path as per Arc90 Lab Documentation
ini_set('include_path', 'arc90_service_twitter/lib');
According the Arc90 documention, we must first set our PHP Path so it will know where to find the Arc90 library.
// Load configuration file
require_once('config.php');
// Load Arc90 Twitter Class
require_once 'Arc90/Service/Twitter.php';
Secondly, we must load our configuration files.
/* Response format. */ $format = 'json'; // Create the Twitter Object $twitter = new Arc90_Service_Twitter(TWITTER_USER, TWITTER_PASS);
In this example, we are going to use the JSON format for all incoming tweets. We will also need to create our Twitter Service Object.
Create A New Twitter Message (twitter.php)
// ------- POST A NEW TWITTER MSG
// -----------------------------------------------------
if(array_key_exists('text', $_POST))
{
$msg = $_POST['text'];
$twitter->updateStatus($msg);
header('location: index.php');
exit();
}
If a user submits the form, the above code checks that the 'text' input field exists. In your code, it may be a good idea to make sure that this field is not blank.
The text field data is then saved to $msg and then passed to the updateStatus($msg) function. And that's it! The user is then redirected to the index page and should be able to view their new tweet.
View Twitter Messages
// ------- GET THE TWITTER TIMELINE
// -----------------------------------------------------
$reply = $twitter->getUserTimeline($format);
if($reply->isError())
{
$tweet_status = '<h3>Twitter Error</h3> Sorry. Twitter is currently experiencing some difficulties';
}
else
{
$rsReplies = json_decode($reply, true);
$i = 0;
$tweets = array();
foreach($rsReplies as $reply)
{
if($i > 2) { break; } // Limit to 3 tweets
$formatted_tweet = format_tweet($reply['text']);
// Populate the array
$tweets[$i]['tweet'] = $formatted_tweet;
$tweets[$i]['time'] = get_elapsedtime(strtotime($reply[created_at]));
$i++;
}
}
Finally, the above code is what actually retrieves your twitter messages.
Using the 'format' we set earlier (JSON), the $twitter->getUserTimeline($format) retrieves your messages and then saves the results to the $reply variable. You can also use 'xml', 'rss', 'atom' for possible data formats.
If there were no errors reported, the system then decodes your JSON data into a PHP array. We then loop through the array (saving the required data into a new array called $tweets) limiting to three messages. You can also note that this is where the two utility functions from the config.php file are used.
If you want more than three messages, you can set the following line as follows:
if($i > 4) { break; } // Limit to 5 tweets
Create the index.php
The index.php file contains all the standard HTML and Javascript code. Basically, think of this file as the 'View' of your application.
<SCRIPT LANGUAGE="JavaScript">
function CountLeft(field, count, max) {
if (field.value.length > max)
field.value = field.value.substring(0, max);
else
count.value = max - field.value.length;
}
</script>
The Javascript code just basically calculates the number of characters that are left. We set this (below) to 140 characters to mimic Twitter's character limit.
<?php if( ! empty($tweet_status)) { ?>
<div class="status"><?php echo $tweet_status; ?></div>
<?php } ?>
<?php foreach($tweets as $tweet) { ?>
<div class="tweet">
<div class="tweeticon"><img src="images/icon-tweet.png"></div>
<div class="tweetmsg"><?php echo $tweet['tweet']; ?>
<br/><span class="datecreated"><?php echo $tweet['time']; ?></span></div>
</div>
<div class="hr"></div>
<?php } ?>
In the twitter.php we did a check to see if the API replied with an error. If so, the code populated a variable called $tweet_status. If this variable is not blank, the error will be displayed to the user.
We then run the $tweets (remember it's an array from twitter.php) through a for loop. Within this loop, we can display each twitter message.
<form method="post" action="twitter.php"> <h1>ADD A NEW MESSAGE</h1> <input name="text" class="tweettxt" type="text" maxlength="140" onKeyDown="CountLeft(this.form.text,this.form.left,140);" onKeyUp="CountLeft(this.form.text,this.form.left,140);"> <br/><input readonly type="text" name="left" size=3 maxlength=3 value="140" class="leftmsg">characters left <br/><input type="submit" value="Tweet" class="submit"> </form>
The above form passes only one form field to twitter.php; the $_POST['text'] variable. You will also notice how I implemented the Javascript function CountLeft within the code to display the number of characters left. One thing to note: the character counter wanted a form field with the name = 'left'. I didn't want it to look like a form field, so with some CSS magic, I removed the form field itself, so it just looks like a text string. You can see how I did that in the 'leftmsg' CSS class.
I urge to download the code from my Git repository and play around with it. Like I mentioned earlier, this tutorial doesn't access the OAuth library, but I may do that in the near future.



RSS Feed
Tweet This Article
EMAIL ME
hi guys...
hi guysI would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well and i have start my own blog now, , thanks for your effort...
Buy:Super Active ED Pack.VPXL.Tramadol.Maxaman.Propecia.Cialis Super Active+.Viagra Professional.Soma.Cialis Soft Tabs.Cialis.Viagra Super Active+.Viagra Super Force.Cialis Professional.Viagra Soft Tabs.Levitra.Zithromax.Viagra....
...
One more new write-up with powerful points, I’ve been a lurker below for just a short time but desire to get significantly additional engaged inside future....