Twitter Search API Tutorial for PHP

Showing tweets on your websites is a great way to attract your sites visitors to follow you on Twitter and the dynamic content might help that your website will be indexed more often by Google. Using the Twitter search API it’s possible to include those tweets right in your website, just like regular HTML with text and links.

This tutorial will show you how to add tweets to your site the easy way, while using an easy to use and powerful PHP library. Before you can start you need to create a Twitter app to get the required credentials to access the Twitter OAuth REST API. Login to your Twitter account and continue to the Twitter developers section.

Once you got your Consumer Key (API Key), Consumer Secret (API Secret), Access Token and Access Token Secret you can use the PHP library to access the Twitter search API.

The Twitter PHP library class

I really like to write my own code, but sometimes it’s pretty stupid to re-invent the wheel. The project TwitterOAuth by Abraham Williams is a great PHP library you can use for all interactions with the Twitter OAuth REST API.

Requirements: PHP 5.4 (If your hosting provider is using an older PHP version, it’s time to move or upgrade!)

You can install the PHP class in two ways, using Composer or manually. For this tutorial I use the manual way because Composer isn’t available for all users. If you have used Composer before, I’m sure you know how to use it for TwitterOAuth as well. Download the ZIP file, extract and upload the directory “twitteroauth-master” to your web server. Create also a new PHP file with the name twitterfeed.php and add the following code.

require_once "twitteroauth-master/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

define('CONSUMER_KEY', 'enter yours');
define('CONSUMER_SECRET', 'enter yours');
define('ACCESS_TOKEN', 'enter yours');
define('ACCESS_TOKEN_SECRET', 'enter yours');

With the code above, we require the autoload.php file which needs to exists in a sub-directory on the location were your file twitterfeed.php is saved. Don’t forget to enter the credentials you got for your Twitter app.

Twitter search API example code

Okay let’s create a first and simple object to get the last 5 entries from your own Twitter timeline:

$conn = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$tweets = $conn->get("statuses/user_timeline", array("count" => 5, "exclude_replies" => true));
foreach ($tweets as $tweet) {
	echo '<p>'.$tweet->text.'<br>Posted on: <a href="https://twitter.com/'.$tweet->user->screen_name.'/status/'.$tweet->id.'">'.date('Y-m-d H:i', strtotime($tweet->created_at)).'</a></p>';
}

In my Twitter search API example I’ve used the different objects to get the tweet text, date and status URL. Use print_r($tweet) to check which object elements are available. For the “get” method I’ve used the endpoint “statuses/user_timeline” to receive the updates from my own time line. Check this Twitter REST API documentation for the available endpoints and methods. This tutorials is about the Twitter search API and that’s why I use “search/tweets” as the endpoint in my next example.

$conn = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$query = array(
	"q" => "#wordpress",
	"count" => 5,
	"result_type" => "recent"
);
$tweets = $conn->get('search/tweets', $query);
foreach ($tweets->statuses as $tweet) {
	echo '<p>'.$tweet->text.'<br>Posted on: <a href="https://twitter.com/'.$tweet->user->screen_name.'/status/'.$tweet->id.'">'.date('Y-m-d H:i', strtotime($tweet->created_at)).'</a></p>';
}

You can see while using the “search/tweets” endpoint, it’s possible to have more options for each search. You can use the same search operators like for a regular search on the Twitter website. The Twitter API documentation offers plenty information and examples. You can choose from different result types: mixed, recent and popular. Furthermore you can select the location and the language to get tweets for your local area.

Use Memcache for your Twitter search results

The Twitter API is very fast an reliable, but if your website has many visitors a cache function is necessary. In my tutorial I’m using functions from PHP Memcache extension.

$search = 'PHP tutorials';
$obj_str = 'tweets_'.str_replace(' ', '_', $search);
$memcache_obj = new Memcache;
$memcache_obj->connect("127.0.0.1", 11211);

if (!$tweets = $memcache_obj->get($obj_str)) {
	$conn = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
	$query = array(
		"q" => $search,
		"count" => 5,
		"result_type" => "recent"
	);
	$tweets = $conn->get('search/tweets', $query);
	if (!empty($tweets->statuses)) {
        $memcache_obj->set($obj_str, $tweets, 0, 3600);
    }
}
if (!empty($tweets->statuses)) {
	foreach ($tweets->statuses as $tweet) {
		echo '<p>'.$tweet->text.'<br>Posted on: <a href="https://twitter.com/'.$tweet->user->screen_name.'/status/'.$tweet->id.'">'.date('Y-m-d H:i', strtotime($tweet->created_at)).'</a></p>';
	} 
} else {
	echo '<p>No tweets for this query.</p>';
}

To get a unique key for the Memcache object, I use the search value plus a prefix. Than I need to create the Memcache object and test if there is already a valid object. If this is true, the stored object is used and otherwise script will execute the code to get new tweets. New tweets are only cached if there are one or more tweet status objects available. For the loop, I’ve added an IF statement to check the availability of status objects first. If not a message shows up. You can use this code right in your project, but maybe your like to show different information for each tweet result. Check all available nodes in the tweet object and build your own dynamic tweet result list. 

Published in: PHP Scripts