PHP snippets to interact with Twitter

by Jean. 28 Comments -

Twitter is an awesome tool for website owners, and you should definitely integrate it into your website if you want to attract more traffic and new visitors. Today, let’s take a look at some 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">\\0</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/

Comments (28) - Leave yours

  1. Tim Lytle said:

    Here’s the first two snippets consolidated into 4 lines (not including the example code). Also, makes it easy to get to all of the data returned by ‘users/show.xml’

    https://gist.github.com/667833

  2. Jon said:

    Amazing, super helpful. I was using a plugin for showing number of twitter followers – always love to be able to add things into the theme directly instead. Thanks again.

  3. Eugen R. said:

    Practically for all of these, you can use the JSON API format and save on preg stuff (which is heavy and ugly).

    On the example of the first snippet:


    function get_followers($twitter_id) {
    $get = file_get_contents('http://twitter.com/users/show.json?screen_name='.$twitter_id);
    $res = json_decode($get);

    return $res->followers_count;
    }

  4. Michiel said:

    Beware of the example you’ve used for updating your status: when a user is not already logged in to Twitter, the given status will be discarded by Twitter.

    Instead, use the following (note: “/home”):
    “http://twitter.com/home?status=@catswhocode Hi Jean, how are you?”

    That will redirect a user to the login screen, and forward them to a page where he will see the specified status, waiting to be tweeted.

    Subtile difference. ;-)

  5. Jamie said:

    Nice! I’m going to implement this on my sites. Thanks for sharing especially in your effort to include snippets just so we could follow the instructions.

  6. kathy said:

    salut jean baptiste. i don’t think the tweetmeme counts links that were retweeted with the bitly link shortening snippet. any idea how to make the 2 play together?

  7. Alex Vallejo said:

    Can someone describe in layman’s terms how cURL is used in conjunction with PHP to display your Tweets

    -noob php developer

  8. Adam Wadsworth said:

    I’m using the ‘Get latest Twitter status’ it works good but its only grabbing the first one is they anyway I can change the amount grabbed ? also links within the Twitter posts are showing up like ‘http://www.example.com%5C%22%5C%5C0%5C%22′ How would I go around amending this ?

  9. Ben Walker said:

    So glad I stumbled on this resource. I just got set up creating a new blog on WordPress using a WooTheme. Been looking for some ways to tweak the PHP to bring a bit more attention to my Twitter account.

    You’ve made things super easy and saved me time. For that, I am grateful!

    Ben

  10. Zach said:

    Lucky to have stumbled on this post. We’re looking to redesign our page for the new year and this looks like it’s worth a try. Thanks a lot! Do you have posts discussing PHP interactions with other social media outlets?

Leave a Reply

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

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!