PHP snippets to interact with Twitter

Get number of Twitter followers

Have you seen my blog sidebar? I display the number of followers I have in full text. This is actually pretty easy to do. The first thing you need is this function:

function get_followers($twitter_id){
	$xml=file_get_contents('http://twitter.com/users/show.xml?screen_name='.$twitter_id);
	if (preg_match('/followers_count>(.*)</',$xml,$match)!=0) {
		$tw['count'] = $match[1];
	}

	return $tw['count'];
}

Once you have the function, you can call it as shown below:

$nb =  get_followers('phpsnippets');
echo "PHP Snippets already have ".$nb." followers!";

» Credit: http://www.phpsnippets.info/get-twitters-followers-in-php

Get latest Twitter status

Using PHP and cURL, it is pretty easy to get the status of a specific user. Once you have it, what about displaying it on your blog, like I do in WPRecipes footer?

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="%5C%22%5C%5C0%5C%22">\</a>', $status);
    return($status);
}

The function is extremely easy to use:

echo get_status('catswhocode');

» http://www.phpsnippets.info/get-twitter-status-using-php

Link to update status, without encoding problems

Many websites and blogs show you how to create a link to Twitter that will update your status. But unfortunely, most websites don’t explain what you need to do in order to avoid encoding problems of spaces and special characters.

<a href="http://twitter.com?status=@catswhocode Hi Jean, how are you?">Tweet!</a>

So, where’s the change? Pretty simple: Just note that I havent linked to http://www.twitter.com, but to http://twitter.com, without the www.

A working example can be seen on my company website: http://www.webdevcat.com/contact.

Get number of retweets for a specific page

Most bloggers are using the Tweetmeme widget to display the number of retweets of their posts. Did you know that Tweetmeme also has an API you can use to get how many times a specific url has been retweeted?

The following function will get the number of RT’s of the url passed as a parameter:

function tweetCount($url) {
    $content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
    $element = new SimpleXmlElement($content);
    $retweets = $element->story->url_count;
    if($retweets){
        return $retweets;
    } else {
        return 0;
    }
}

Using the function is easy, as you can expect:

echo tweetCount('http://www.catswhocode.com');

Note that the Twitter API also provide a way to get the number of retweets. See http://urls.api.twitter.com/1/urls/count.json?url=www.google.com for example.

» http://www.phpsnippets.info/get-how-many-times-a-page-have-been-retweeted-using-php

Testing friendship between two users

If you want to know if a specific user is following you (or someone else) you have to use the Twitter API. This snippet will echo true if the two users specified on lines 18 and 19 are friends. It will return false otherwise.

/* makes the request */
function make_request($url) {
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

/* gets the match */
function get_match($regex,$content) {
	preg_match($regex,$content,$matches);
	return $matches[1];
}

/* persons to test */
$person1 = 'phpsnippets';
$person2 = 'catswhocode';

/* send request to twitter */
$url = 'https://api.twitter.com/1/friendships/exist';
$format = 'xml';

/* check */
$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);
$result = get_match('/<friends>(.*)<\/friends>/isU',$persons12);
echo $result; // returns "true" or "false"

» http://www.phpsnippets.info/get-twitter-status-using-php

Shorten urls for Twitter

As you know if you’re a Twitter user, you can’t post messages which are longer than 140 characters. To avoid this problem, you have to use an url shortener. There’s lots of different url shorteners on the internet. TinyUrl.com is one of them, it doesn’t produce the shortest urls but what I really love it is that you don’t need to have an account to use it with PHP.

The following function takes a long url as a parameter and return a shorter url, using the TinyUrl url shortener.

function getTinyUrl($url) {
    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
}

» http://www.phpsnippets.info/convert-url-to-tinyurl

Shorten urls using Bit.ly

In the previous snippet of that article, I’ve shown you how you can shorten your urls using TinyUrl.com. This is cool, but I’m pretty sure some of you prefer using the bit.ly service. No problem, you can still use PHP to get your shortened url.

function bitly($url) {
	$content = file_get_contents("http://api.bit.ly/v3/shorten?login=YOURLOGIN&apiKey=YOURAPIKEY&longUrl=".$url."&format=xml");
	$element = new SimpleXmlElement($content);
	$bitly = $element->data->url;
	if($bitly){
		return $bitly;
	} else {
		return '0';
	}
}

To use the function, simply use the following:

echo bitly("http://www.catswhocode.com");

» http://woorkup.com/2010/06/06/3-practical-wordpress-code-snippets-you-probably-must-know/

Like CatsWhoCode? If yes, don’t hesitate to check my other blog CatsWhoBlog: It’s all about blogging!

PHP snippets to interact with Twitter

Leave a Reply

Your email address will not be published. Required fields are marked *