Use your left/right keys to browse tutorials
Using the Twitter Search API

Using the Twitter Search API

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on January 30, 2009

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



More tutorials from Papermashup
  • Rod

    Hashes weren’t working – also spaces were yielding incorrect results. On twitter if you search two keywords it finds results with BOTH, with yours it would find results with EITHER. To fix both of these you need to redefine the URL encoding after pulling down the info with GET – eg;

    $q = str_replace(” “, “%20″, $q); // put the space code back
    $q = str_replace(“#”, “%23″, $q); // put the hash code back

    Should fix it up.

    • http://www.papermashup.com Ashley

      @Rod you’ll need to urlencode() the search query thats passed to the xml file, it’s something i missed out in the example code. Hope that helps.

  • Rod

    Looks great at first glance, but for some reason I can’t get the demo to work with hash tags… #anything returns no results… intentional? it’s a pretty crucial omission for me

  • Vincent

    Appreciate your doing this,worthing learning. I try to integrate google translate API or other translate jQuery into this.so I can translate the search result to any language.

  • vincent

    it cool,is it possibel to show the tweet time in the tweeet

    • http://www.papermashup.com Ashley

      @vincent I’ve updated the demo and download to include the time as well as a function to work out the time since a tweet was posted.

  • nick

    Isn’t it standard practice to include the original tweeter when retweeting?

    Also then there is a ‘ it cuts off the rest of the message.

    • http://www.papermashup.com Ashley

      @nick yeah it is, i added the retweet as an example you are more than welcome to extend the script for your own use.

  • nick

    Awesome. I have almost 0 php skills and this was the only thing missing.

    Thanks!

  • nick

    Hey,

    Is it possible to add a retweet button to each of the results?

    • http://www.papermashup.com Ashley

      @nick I’ve updated the script and added a retweet button, you could extend this and mash it with my ‘using the twitter api’ post to make it automatic but as a simple example you click the re-tweet button and it adds the status in the twitter form.

      Hope that helps

  • Pingback: Mootools Ajax Example | Ashley Ford - PaperMashup.com

  • Pingback: Enlaces del 31-01-09 | evelio.info

  • Simon Lewis

    Great tutorial this is exactly what i was looking for an app im building thanks Ashley

  • Ashley

    Hey Simon,

    Glad you found it useful, thanks for dropping by!