Using the Twitter Search API

Twitters new search feature is great for finding interesting people and topics to follow. So i wrote a script to get search results from twitter and display them on your site. This could be integrated into an existing application or used standalone to follow a particular topic or keyword on twitter,  Check the Demo.

twitter-search

The script uses PHP and CURL to get the twitter search results to display them on the page. for the demo i’ve set an if statement to display results for ‘papermashup.com’ if no get variable is present.

Here’s the code that allows us to enter our search term, on submit it posts a get variable to the URL which PHP then processes with CURL.

<div id="search">
<form action="" method="get">
  <label>
  Search twitter
  <input type="text" name="q" id="searchbox" />
  <input type="submit" name="submit" id="submit" value="Search" />
  </label>
</form>
</div>

So we use PHP, CURL, and the SimpleXMLElement() class in PHP5 to parse the XML file. Once we have the xml data, regular expression is used to find the links in the xml content element, which is then saved in $description.

The Code:


// Date function (this could be included in a seperate script to keep it clean)
function date_diff($d1, $d2){
	$d1 = (is_string($d1) ? strtotime($d1) : $d1);
	$d2 = (is_string($d2) ? strtotime($d2) : $d2);

	$diff_secs = abs($d1 - $d2);
	$base_year = min(date("Y", $d1), date("Y", $d2));

	$diff = mktime(0, 0, $diff_secs, 1, 1, $base_year);
	$diffArray = array(
		"years" => date("Y", $diff) - $base_year,
		"months_total" => (date("Y", $diff) - $base_year) * 12 + date("n", $diff) - 1,
		"months" => date("n", $diff) - 1,
		"days_total" => floor($diff_secs / (3600 * 24)),
		"days" => date("j", $diff) - 1,
		"hours_total" => floor($diff_secs / 3600),
		"hours" => date("G", $diff),
		"minutes_total" => floor($diff_secs / 60),
		"minutes" => (int) date("i", $diff),
		"seconds_total" => $diff_secs,
		"seconds" => (int) date("s", $diff)
	);
	if($diffArray['days'] > 0){
		if($diffArray['days'] == 1){
			$days = '1 day';
		}else{
			$days = $diffArray['days'] . ' days';
		}
		return $days . ' and ' . $diffArray['hours'] . ' hours ago';
	}else if($diffArray['hours'] > 0){
		if($diffArray['hours'] == 1){
			$hours = '1 hour';
		}else{
			$hours = $diffArray['hours'] . ' hours';
		}
		return $hours . ' and ' . $diffArray['minutes'] . ' minutes ago';
	}else if($diffArray['minutes'] > 0){
		if($diffArray['minutes'] == 1){
			$minutes = '1 minute';
		}else{
			$minutes = $diffArray['minutes'] . ' minutes';
		}
		return $minutes . ' and ' . $diffArray['seconds'] . ' seconds ago';
	}else{
		return 'Less than a minute ago';
	}
}

// Work out the Date plus 8 hours
// get the current timestamp into an array
$timestamp = time();
$date_time_array = getdate($timestamp);

$hours = $date_time_array['hours'];
$minutes = $date_time_array['minutes'];
$seconds = $date_time_array['seconds'];
$month = $date_time_array['mon'];
$day = $date_time_array['mday'];
$year = $date_time_array['year'];

// use mktime to recreate the unix timestamp
// adding 19 hours to $hours
$timestamp = mktime($hours + 0,$minutes,$seconds,$month,$day,$year);
$theDate = strftime('%Y-%m-%d %H:%M:%S',$timestamp);	

// END DATE FUNCTION

//Search API Script

$q=$_GET['q'];

if($_GET['q']==''){

$q = 'papermashup.com';}

$search = "http://search.twitter.com/search.atom?q=".$q."";

$tw = curl_init();

curl_setopt($tw, CURLOPT_URL, $search);
curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);
$twi = curl_exec($tw);
$search_res = new SimpleXMLElement($twi);

echo "<h3>Twitter search results for '".$q."'</h3>";

## Echo the Search Data

foreach ($search_res->entry as $twit1) {

$description = $twit1->content;

$description = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", $description);
$description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" >\\2</a>'", $description);
$description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://\\2\" >\\2</a>'", $description);

$retweet = strip_tags($description);

$date =  strtotime($twit1->updated);
$dayMonth = date('d M', $date);
$year = date('y', $date);
$message = $row['content'];
$datediff = date_diff($theDate, $date);

echo "<div class='user'><a href=\"",$twit1->author->uri,"\" target=\"_blank\"><img border=\"0\" width=\"48\" class=\"twitter_thumb\" src=\"",$twit1->link[1]->attributes()->href,"\" title=\"", $twit1->author->name, "\" /></a>\n";
echo "<div class='text'>".$description."<div class='description'>From: ", $twit1->author->name," <a href='http://twitter.com/home?status=RT: ".$retweet."' target='_blank'>Retweet!</a></div><strong>".$datediff."</strong></div><div class='clear'></div></div>";

}

curl_close($tw);


UPDATE 25/03/09: i’ve added a re-tweet button which simply opens twitter putting the update in your status window.

UPDATE 26/04/09: As requested by @vincent below. I’ve added a time function which works out how long ago a tweet was posted

demodownload

This entry was posted in API's, Downloads, PHP, Tutorials, popular and tagged , , , , , , , . Bookmark the permalink.
Comments
63 discussions around Using the Twitter Search API
Older Comments
  1. Maria says:

    Please, I have the same error:

    Fatal error: Cannot redeclare date_diff() in C:\xampp\htdocs\twitta\twitter-search.php on line 106

    Somebody can help me?

  2. Aejaz says:

    Hello Ashley,

    Thanks for the Nice tutorial.

    I need a help in pagination.

    my query is how can i retrieve all the tweets max it is 1500 given limit in the api.
    I want to show all the tweets in my php page with pagination.1234…. or previous | next

    how can i do that pls help me out.

    I am able to receive 100 tweets for one page.
    how can i paginate the remaining tweets the rest of 1400 tweets of other page.

    like we have rpp=20&page=1 how can i increment this page name so that i can navigate all the 1500 tweets.

    Thanks,
    Aejaz

  3. Phil says:

    @Maria @carlos I had the same problem as you. I don’t know why I hit the issue but if you just rename the date_diff function to something else and then change the name where the function is called lower down the page then it should work.

  4. saief says:

    Can I use this search script to create my own twitter search engine. if so how can i do that. i am not tech person just wanted to know for my class project. so can please help me

  5. saief says:

    Hi. Do you think you can add real time search feature, Twitter Trends, your search, Key word search… i would like to know how its works.

  6. Ramesh says:

    In that search result page, I am getting very limited results like(15) only,how can i get all the related result.

  7. Ramesh says:

    Could you please help for search result pagination

  8. Ashley says:

    @ Ramesh,

    I think the search results are limited, although im not sure by how many you could probably get several hundred results try &count=500 at the end of the CURL XML request.

    Ashley

  9. babar says:

    Grate tutorial …..
    Can u kindly help me, I am trying to get a count of total tweeks on twitter that contain a specific search word. What I tried is after parse the atom feed using simplexml, I use the ‘count’ method to get the number of “entry” items. But it gives probably what is returned in one feed while I want to get count of all tweets on twitter.

  10. Nishant says:

    Hi Ashley,

    Thanks for sharing this nice tutorial. I am running XAMPP on Windows XP and when I am writing the above script, I am getting the following error:

    “Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\Automation Tool\cURL.php on line 2″

    I searched on internet and found that I have to do two things in order for cURL to work for Windows:
    1. Uncomment extension=php_curl.dll in the PHP.INI file.
    2. Copy the below two dll files from PHP folder and put it under windows/system32 dir.
    ssleay32.dll
    libeay32.dll

    I have done it but still its not working. Please help.

  11. Nishant says:

    Hi Ashley,

    Thanks for sharing this nice tutorial. I am running XAMPP on Windows XP and when I am writing the above script, I am getting the following error:

    “Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\Automation Tool\cURL.php on line 2″

    I searched on internet and found that I have to do two things in order for cURL to work for Windows:
    1. Uncomment extension=php_curl.dll in the PHP.INI file.
    2. Copy the below two dll files from PHP folder and put it under windows/system32 dir.
    ssleay32.dll
    libeay32.dll

    I have done it but still its not working. Please help me.

  12. Nishant says:

    Hi Ashley,

    I got the solution, I needed to restart my Apache and now cULR is working.
    Thanks

  13. Tino says:

    Thanks for this great tutorial Asley.

    I tried the code in my localhost and get an error like Carlos was get.

    Fatal error: Cannot redeclare date_diff() in C:\xampp\htdocs\twitta\twitter-search.php on line 106

    I hope you have a time to solve the problem.

    Thanks

Older Comments

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribers
1,250
Twitter
510
Comments
1,207
Posts
125