How to Pull a Twitter Feed Into Your Site Using PHP, MySQL, and the Twitter API

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.

These days, Twitter feeds are everywhere, it seems. There are a million widgets, gadgets, and doohickeys that let you pull your Twitter posts onto your site, but the problem with all of them is that they're tough to customize. Suppose you want to be able to grab from multiple Twitter feeds? Or omit any tweets that contain URLs or certain flagged words? With those widgets, it's tough to do. That's why I figured out how to gather my Tweets on my own. I imagine a few other people out there will want to do the same. Hopefully this tutorial will save them (you) some time. Enjoy. And, leave any related suggestions/code/questions in the comments at the bottom.

  1. Create a MySQL table to store the tweets. The Twitter API has limits set on how often you can ping it. So, you'll need to store your tweets locally and update it periodically using a cron job. The first step in doing that is creating a place to store the data. Copy and paste the following MySQL code into phpMyAdmin (or whatever tool you use to connect to your MySQL server):
    CREATE TABLE `twitter` (
    `screen_name` VARCHAR( 255 ) NOT NULL ,
    `text` VARCHAR( 255 ) NOT NULL ,
    `hidden` CHAR( 1 ) NOT NULL ,
    PRIMARY KEY ( `id` ) 
  2. Create a cron job that grabs the tweets from the Twitter API and stores it in your table. Create a PHP file (named /cron/twitter-update.php in this example) with the following code:
    1.   <?php
    3.   require_once '' ; //custom database functions
    5.   function saveTweets($screen_name) {
    6.   	global $link;
    8.   	$screen_name = dbEscape(strtolower(trim($screen_name)));
    9.   	if (!$screen_name) { echo "<p><strong>Error: No screen name declared.</strong></p>\n"; return false; }
    11.  	$row = dbGetRow("SELECT `id` FROM `twitter` WHERE `screen_name`='$screen_name' ORDER BY `id` DESC LIMIT 1");
    12.  	$last_id = $row['id'];
    14.  	$url = "$screen_name" ;
    15.  	if ($last_id) { $url .= "&since_id=$last_id" ; }
    16.  	$ch = curl_init($url);
    17.  	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
    18.  	$xml = curl_exec ($ch);
    19.  	curl_close ($ch);
    21.  	$affected = 0;
    22.  	$twelement = new SimpleXMLElement($xml);
    23.  	foreach ($twelement->status as $status) {
    24.  		$text = dbEscape(trim($status->text));
    25.  		$time = strtotime($status->created_at);
    26.  		$id = $status->id;
    27.  		dbQuery("INSERT INTO `twitter` (`id`,`screen_name`,`time`,`text`,`hidden`) VALUES ('$id','$screen_name','$time','$text','n')");
    28.  		$affected = $affected + dbAffectedRows();
    29.  	}
    31.  	return "<p>".number_format($affected)." new tweets from $screen_name saved.</p>\n" ;
    32.  }
    34.  echo saveTweets('inkplant');
    36.  ?>
  3. Add the cron job to your crontab file. You need to let your server know how often to run this new file that you created. In the example below, it will run every 5 minutes. Go to your Unix shell and type crontab -e and then add the following line:
    1.   */5 * * * * /usr/bin/php /cron/twitter-update.php
    Note: The settings your server uses to run cron jobs can vary a lot. Check with your server admin for instructions specific to your machine if the example above doesn't work.
  4. Pull the databased content to your web page. Place the following code within the body of your PHP page where you'd like to display the Twitter feed. Of course, you can customize here as much as you want...
    1.   <?php
    3.   echo "<ul class=\"twitter_feed\">\n" ;
    4.   $result = dbQuery("SELECT * FROM `twitter` WHERE `screen_name`='inkplant' AND `hidden` != 'y' ORDER BY `time` DESC LIMIT 10");
    5.   while ($row = dbGetRow($result)) {
    6.   	$text = stripslashes($row['text']);
    7.   	$time = $row['time'];
    8.   	echo "  <li><span class=\"twitter_time\">".date('M j, Y, g:i a',$time)."</span> &middot; $text</li>\n" ;
    9.   }
    10.  echo "</ul>\n" ;
    12.  ?>



This post was first published on August 22nd, 2010 and last updated on March 13th, 2014 by Robert James Reese in the following categories: cURL, MySQL, 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.