Get All Twitter Posts of a Specific Hashtag in PHP

Note: The Twitter REST API v1 – which this script calls – is no longer active. I haven't had a chance to upgrade this article to API v1.1 yet.

I got a response to my article about pulling a Twitter feed into your site with PHP asking how to pull all tweets for a given #hashtag. Here, I have published a function that allows you to do so… It's not saved into a database, you'll have to do that yourself, but this should be enough to get you started.

1.   <?php
2.   
3.   function getTweets($hash_tag) {
4.   
5.   	$url = 'http://search.twitter.com/search.atom?q='.urlencode($hash_tag) ;
6.   	echo '<p>Connecting to <strong>'.$url.'</strong>&hellip;</p>';
7.   	$ch = curl_init($url);
8.   	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
9.   	$xml = curl_exec ($ch);
10.  	curl_close ($ch);
11.  
12.  	//If you want to see the response from Twitter, uncomment this next part out:
13.  	echo '<p>Response:</p>';
14.  	echo '<pre>'.htmlspecialchars($xml).'</pre>';
15.  
16.  	$affected = 0;
17.  	$twelement = new SimpleXMLElement($xml);
18.  	foreach ($twelement->entry as $entry) {
19.  		$text = trim($entry->title);
20.  		$author = trim($entry->author->name);
21.  		$time = strtotime($entry->published);
22.  		$id = $entry->id;
23.  		echo '<p>Tweet from '.htmlspecialchars($author).': <strong>'.htmlspecialchars($text).'</strong>  <em>Posted '.date('n/j/y g:i a',$time).'</em></p>';
24.  	}
25.  
26.  	return true ;
27.  }
28.  
29.  ?>

There are a lot of options with the Twitter Search method. You can find out more by checking out their documentation.


Comments

Loading…

This post was first published on May 31st, 2011 and last updated on June 28th, 2014 by Robert James Reese in the following categories: PHP and Twitter. Before using any of the code or other content in this post, you must read and agree to our terms of use.