9 Useful Twitter Code Snippets


1. Retrieve Twitter Status using PHP and XML

This is the beginning of my retrieval of twitter status class…just something im playing with right now. It retrieves the xml, saves it on your server, then you can either use javascript or php to traverse the xml tree.

[php]
<?php

class xmlmanager{

private $twitterXML;
private $twitterURL = ""; //insert xml url here
private $dom;

function __construct(){

}

function GetTwitterXML(){

$this->twitterXML = simplexml_load_file($this->twitterURL);

return ;

}

function save_twitter_xml_as_file(){
$this->dom = new DOMDocument();
$this->dom->loadXML($this->twitterXML->asXML());
$this->dom->saveXML();
$this->dom->save(‘mytwitter.xml’);
return ;
}

function __destruct(){

}
}

?>
[/php]

source : http://snipplr.com/view/28676

2. Most recent Twitter status

[php]
<?php
function get_status($twitter_id, $hyperlinks = true) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$src = curl_exec($c);
curl_close($c);
preg_match(‘/<text>(.*)<\/text>/’, $src, $m);
$status = htmlentities($m[1]);
if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a href=\"\\0\">\\0</a>", $status);
return($status);
}
?>
[/php]

source : http://snipplr.com/view/28332

3. Display recent Twitter tweets using PHP

If you’ve ever wanted to display your latest Twitter tweets on a website, here is method to do that using PHP.

[php]
<?php

/**
* TWITTER FEED PARSER
*
* @version 1.1.1
* @author Jonathan Nicol
* @link http://f6design.com/journal/2010/10/07/display-recent-twitter-tweets-using-php/
*
* Notes:
* We employ caching because Twitter only allows their RSS feeds to be accesssed 150
* times an hour per user client.
* —
* Dates can be displayed in Twitter style (e.g. "1 hour ago") by setting the
* $twitter_style_dates param to true.
*
* Credits:
* Hashtag/username parsing based on: http://snipplr.com/view/16221/get-twitter-tweets/
* Feed caching: http://www.addedbytes.com/articles/caching-output-in-php/
* Feed parsing: http://boagworld.com/forum/comments.php?DiscussionID=4639
*/

function display_latest_tweets(
$twitter_user_id,
$cache_file = ‘./twitter.txt’,
$tweets_to_display = 100,
$ignore_replies = false,
$twitter_wrap_open = ‘<h2>Latest tweets</h2><ul id="twitter">’,
$twitter_wrap_close = ‘</ul>’,
$tweet_wrap_open = ‘<li><span class="status">’,
$meta_wrap_open = ‘</span><span class="meta"> ‘,
$meta_wrap_close = ‘</span>’,
$tweet_wrap_close = ‘</li>’,
$date_format = ‘g:i A M jS’,
$twitter_style_dates = false){

// Seconds to cache feed (1 hour).
$cachetime = 60*60;
// Time that the cache was last filled.
$cache_file_created = ((@file_exists($cache_file))) ? @filemtime($cache_file) : 0;

// A flag so we know if the feed was successfully parsed.
$tweet_found = false;

// Show file from cache if still valid.
if (time() – $cachetime < $cache_file_created) {

$tweet_found = true;
// Display tweets from the cache.
@readfile($cache_file);

} else {

// Cache file not found, or old. Fetch the RSS feed from Twitter.
$rss = @file_get_contents(‘http://twitter.com/statuses/user_timeline/’.$twitter_user_id.’.rss’);

if($rss) {

// Parse the RSS feed to an XML object.
$xml = @simplexml_load_string($rss);

if($xml !== false) {

// Error check: Make sure there is at least one item.
if (count($xml->channel->item)) {

$tweet_count = 0;

// Start output buffering.
ob_start();

// Open the twitter wrapping element.
$twitter_html = $twitter_wrap_open;

// Iterate over tweets.
foreach($xml->channel->item as $tweet) {

// Twitter feeds begin with the username, "e.g. User name: Blah"
// so we need to strip that from the front of our tweet.
$tweet_desc = substr($tweet->description,strpos($tweet->description,":")+2);
$tweet_desc = htmlspecialchars($tweet_desc);
$tweet_first_char = substr($tweet_desc,0,1);

// If we are not gnoring replies, or tweet is not a reply, process it.
if ($tweet_first_char!=’@’ || $ignore_replies==false){

$tweet_found = true;
$tweet_count++;

// Add hyperlink html tags to any urls, twitter ids or hashtags in the tweet.
$tweet_desc = preg_replace(‘/(https?:\/\/[^\s"<>]+)/’,'<a href="$1">$1</a>’,$tweet_desc);
$tweet_desc = preg_replace(‘/(^|[\n\s])@([^\s"\t\n\r<:]*)/is’, ‘$1<a href="http://twitter.com/$2">@$2</a>’, $tweet_desc);
$tweet_desc = preg_replace(‘/(^|[\n\s])#([^\s"\t\n\r<:]*)/is’, ‘$1<a href="http://twitter.com/search?q=%23$2">#$2</a>’, $tweet_desc);

// Convert Tweet display time to a UNIX timestamp. Twitter timestamps are in UTC/GMT time.
$tweet_time = strtotime($tweet->pubDate);
if ($twitter_style_dates){
// Current UNIX timestamp.
$current_time = time();
$time_diff = abs($current_time – $tweet_time);
switch ($time_diff)
{
case ($time_diff < 60):
$display_time = $time_diff.’ seconds ago';
break;
case ($time_diff >= 60 && $time_diff < 3600):
$min = floor($time_diff/60);
$display_time = $min.’ minutes ago';
break;
case ($time_diff >= 3600 && $time_diff < 86400):
$hour = floor($time_diff/3600);
$display_time = ‘about ‘.$hour.’ hour';
if ($hour > 1){ $display_time .= ‘s'; }
$display_time .= ‘ ago';
break;
default:
$display_time = date($date_format,$tweet_time);
break;
}
} else {
$display_time = date($date_format,$tweet_time);
}

// Render the tweet.
$twitter_html .= $tweet_wrap_open.$tweet_desc.$meta_wrap_open.'<a href="http://twitter.com/’.$twitter_user_id.’">’.$display_time.'</a>’.$meta_wrap_close.$tweet_wrap_close;

}

// If we have processed enough tweets, stop.
if ($tweet_count >= $tweets_to_display){
break;
}

}

// Close the twitter wrapping element.
$twitter_html .= $twitter_wrap_close;
echo $twitter_html;

// Generate a new cache file.
$file = @fopen($cache_file, ‘w’);

// Save the contents of output buffer to the file, and flush the buffer.
@fwrite($file, ob_get_contents());
@fclose($file);
ob_end_flush();

}
}
}
}
// In case the RSS feed did not parse or load correctly, show a link to the Twitter account.
if (!$tweet_found){
echo $twitter_wrap_open.$tweet_wrap_open.’Oops, our twitter feed is unavailable right now. ‘.$meta_wrap_open.'<a href="http://twitter.com/’.$twitter_user_id.’">Follow us on Twitter</a>’.$meta_wrap_close.$tweet_wrap_close.$twitter_wrap_close;
}
}

display_latest_tweets(‘YOUR_TWITTER_ID’);

?>
[/php]

source : http://snipplr.com/view/61700/

4. Display your Twitter entries on your WordPress blog

Integrating a RSS feed is easy, but it is even more on a WordPress blog. The following code allow you to display your 5 most recent Twitter entries on your WordPress blog.

[php]
<?php include_once(ABSPATH . WPINC . ‘/rss.php’);
wp_rss(‘http://twitter.com/statuses/user_timeline/15985955.rss’, 5); ?>
[/php]

source : http://www.wprecipes.com/how-to-display-any-rss-feed-on-your-wordpress-blog

5. Autofollow script (PHP)

This code allow you to automatically follow user who have tweeted about a specific term. For example, if you want to follow all users who tweeted about php, simply give it as a value to the $term variable on line 7.

[php]
<?php
// Twitter Auto-follow Script by Dave Stevens – http://davestevens.co.uk

$user = "";
$pass = "";

$term = "";

$userApiUrl = "http://twitter.com/statuses/friends.json";

$ch = curl_init($userApiUrl);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$apiresponse = curl_exec($ch);
curl_close($ch);
$followed = array();

if ($apiresponse) {
$json = json_decode($apiresponse);
if ($json != null) {
foreach ($json as $u) {
$followed[] = $u->name;
}
}
}

$userApiUrl = "http://search.twitter.com/search.json?q=" . $term . "&rpp=100";
$ch = curl_init($userApiUrl);
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$apiresponse = curl_exec($ch);
curl_close($ch);

if ($apiresponse) {
$results = json_decode($apiresponse);
$count = 20;
if ($results != null) {
$resultsArr = $results->results;
if (is_array($resultsArr)) {
foreach ($resultsArr as $result) {
$from_user = $result->from_user;
if (!in_array($from_user,$followed)) {
$ch = curl_init("http://twitter.com/friendships/create/" . $from_user . ".json");
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"follow=true");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$apiresponse = curl_exec($ch);

if ($apiresponse) {
$response = json_decode($apiresponse);
if ($response != null) {
if (property_exists($response,"following")) {
if ($response->following === true) {
echo "Now following " . $response->screen_name . "\n";
} else {
echo "Couldn’t follow " . $response->screen_name . "\n";
}
} else {
echo "Follow limit exceeded, skipped " . $from_user . "\n";
}
}
}
curl_close($ch);
} else {
echo "Already following " . $from_user . "\n";
}
}
}
}
}
?>
[/php]

source: http://snipplr.com/view/17595/twitter-autofollow-php-script/

6. View who doesn’t follow you (Python)

Some people don’t like the idea of following people who don’t follow you back. If you recognized yourself in this statement, there’s a huge amount of chances that you’ll enjoy the following Python code snippet.
Simply type your Twitter username and password on line 4 and call the file using the Python interpreter.

[php]
import twitter, sys, getpass, os

def call_api(username,password):
api = twitter.Api(username,password)
friends = api.GetFriends()
followers = api.GetFollowers()
heathens = filter(lambda x: x not in followers,friends)
print "There are %i people you follow who do not follow you:" % len(heathens)
for heathen in heathens:
print heathen.screen_name

if __name__ == "__main__":
password = getpass.getpass()
call_api(sys.argv[1], password)
[/php]

source : http://blog.davidziegler.net/post/107429458/see-which-twitterers-don-t-follow-you-back-in-less-than

7. Get the number of follower in full text (PHP)

When you have a website or blog and use Twitter, it can be cool to display how many followers you have. To do so, simply use the short code snippet above.
Note that if you want to integrate the same code into WordPress, using caching, Rarst have written a nice code that you can get using the link after the snippets (Rarst code is in the comments, so scroll down a bit)

[php]
<?php
$xml=file_get_contents(‘http://twitter.com/users/show.xml?screen_name=catswhocode’);
if (preg_match(‘/followers_count>(.*)</’,$xml,$match)!=0) {
$tw[‘count’] = $match[1];
}
echo $tw[‘count’];
?>
[/php]

source: http://www.wprecipes.com/display-the-total-number-of-your-twitter-followers-on-your-wordpress-blog

8. Twitter email grabber (PHP)

You know it, you should never type your email adress on the Internet. This include Twitter. Due to the site popularity, lots of spammers created scripts to grab email adresses from the site. How can they do that? Like that:

[php]
<?php
$file = file_get_contents("http://search.twitter.com/search?q=gmail.com+OR+hotmail.com++OR+%22email+me%22");
$file = strip_tags($file);

preg_match_all(
"([a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b)siU",
$file,
$matches);

print_r($matches);
?>
[/php]

source : http://www.fromzerotoseo.com/twitter-email-grabber

9. Timeline function

Since Twitter became very popular, I started to hear many people saying that they absolutely love how Twitter display time informations: 1 hour ago, about 7 days ago, less than a minute ago, etc. This is what the function below do.

[php]
function timespan($time1, $time2 = NULL, $output = ‘years,months,weeks,days,hours,minutes,seconds’)
{
$output = preg_split(‘/[^a-z]+/’, strtolower((string) $output));
if (empty($output))
return FALSE;
extract(array_flip($output), EXTR_SKIP);
$time1 = max(0, (int) $time1);
$time2 = empty($time2) ? time() : max(0, (int) $time2);
$timespan = abs($time1 – $time2);
isset($years) and $timespan -= 31556926 * ($years = (int) floor($timespan / 31556926));
isset($months) and $timespan -= 2629744 * ($months = (int) floor($timespan / 2629743.83));
isset($weeks) and $timespan -= 604800 * ($weeks = (int) floor($timespan / 604800));
isset($days) and $timespan -= 86400 * ($days = (int) floor($timespan / 86400));
isset($hours) and $timespan -= 3600 * ($hours = (int) floor($timespan / 3600));
isset($minutes) and $timespan -= 60 * ($minutes = (int) floor($timespan / 60));
isset($seconds) and $seconds = $timespan;
unset($timespan, $time1, $time2);
$deny = array_flip(array(‘deny’, ‘key’, ‘difference’, ‘output’));
$difference = array();
foreach ($output as $key) {
if (isset($$key) AND ! isset($deny[$key])) {
$difference[$key] = $$key;
}
}
if (empty($difference))
return FALSE;
if (count($difference) === 1)
return current($difference);
return $difference;
}
[/php]

source : http://snipplr.com/view.php?codeview&id=19353