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.


function getTweets($hash_tag) {

	$url = ''.urlencode($hash_tag) ;
	echo '<p>Connecting to <strong>'.$url.'</strong>…</p>';
	$ch = curl_init($url);
	$xml = curl_exec ($ch);
	curl_close ($ch);

	//If you want to see the response from Twitter, uncomment this next part out:
	echo '<p>Response:</p>';
	echo '<pre>'.htmlspecialchars($xml).'</pre>';

	$affected = 0;
	$twelement = new SimpleXMLElement($xml);
	foreach ($twelement->entry as $entry) {
		$text = trim($entry->title);
		$author = trim($entry->author->name);
		$time = strtotime($entry->published);
		$id = $entry->id;
		echo '<p>Tweet from '.htmlspecialchars($author).': <strong>'.htmlspecialchars($text).'</strong>  <em>Posted '.date('n/j/y g:i a',$time).'</em></p>';

	return true ;


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



This article 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.