My First Approved Script on CodeCanyon.net
Apr, 2010
20

Last Tweet – A PHP Twitter Class

Sometimes doing something simple should be just that, simple. Thanks to Twitters excellent restful API, I am easily able to grab my last tweet plus some bonus data about my account and display it on my website. So Here it is, simple and clean.

First we have the PHP class file:

class last_tweet{

// The Base URL to Use
protected $base_url = "http://twitter.com/";

// Grab the URL
protected function get_url($uri)
{
// Start the cURL Connection
$connection = curl_init();

// Set Options
curl_setopt($connection, CURLOPT_HEADER, 1);
curl_setopt($connection, CURLOPT_RETURNTRANSFER,1);

// Set the URL to Grab
$fetch_url = $this->base_url . $uri;
curl_setopt($connection, CURLOPT_URL, $fetch_url);

// Get the Page
$page = curl_exec($connection);

// Close the Connection
curl_close($connection);

return $page;
}

// Parses the XML
protected function parse_xml($xml_string)
{
$xml_string = strstr($xml_string, 'get_url($api_call);
$xml = $this->parse_xml($page);

// Return the XML Object
return $xml;
}

public function show_tweet($username, $num)
{
// Grab the tweet
$tweet = $this->get_tweet($username, $num);

//all your display code can go here if you want, Im just returning the array from the simplexmlelement

return $tweet;
}

}

Its pretty simple, nice number of functions to set the cURL transfer, send the request to twitter and return the XML. So the next step is just instantiating the class and doing something with the data from twitter:

include_once('class.last_tweet.php');

//instantiate
$last_tweet = new last_tweet;

//Your Username
$username = 'Your Username';

// number of tweets returned, can be as many as you like. I think twitter limits at 200
$num = '1';

// Grab the Tweet XML
$tweet = $last_tweet->get_tweet($username, $num);

Here I just spit it out on an empty HTML page. You can decided how you want to disseminate the data.

print_r($tweet);

Thats it, get your last tweet info from twitter. Use it wisely, twitter only allows 100 calls an hour to the restful API.

Here is the source code: Last Tweet PHP Class

Cheers!

Post to Twitter Tweet This!

This entry was posted on 04.20.2010 at 5:52 pm and is filed under Code Bin. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Comments

1 Response to “Last Tweet – A PHP Twitter Class”

04.21.2010 | 1:40 am

[...] Continued here: Last Tweet – A PHP Twitter Class | Napolitopia.com [...]

Leave a Reply

Green Web Hosting! This site hosted by DreamHost.