How to Create Your Own Twitter Widget in PHP, Part 1

Share this article

Twitter status widgets are ten a penny, so why create your own? Because you can! Your own widget will always be more customizable than any off-the-shelf solution, and you’ll be the envy of your peers. We’ve also been asked by several readers for articles about the topic, and it’s a great introduction to PHP, REST APIs, JSON, regular expressions and Object Orientated Programming. Twitter widget in PHP

The Challenge

This is a 3-part tutorial based on source code you can download here. Our objectives are to:
    • Interrogate the Twitter API and fetch any number of status updates for an individual user.
    • Apply the data to a configurable HTML template and convert URLs, @id and #hashtags to proper links.
    • Format dates into a friendlier format, e.g. posted ten minutes ago, yesterday, two weeks ago, etc.
    • Cache the widget HTML so the fetching process is not required during every page load.
    • Make the resulting widget work in all browsers — yes, that includes IE6!

      The Twitter API

      Twitter provides a REST API. The following URL fetches the last N tweets posted by a specific user: Where:
      • user_id is the Twitter user name
      • format is either json, xml, rss or atom
      • N is the number of status updates to return
      Therefore, the following URL returns Sitepoint’s last 10 updates in XML format:

      JSON vs XML?

      The future of XML is a hot discussion topic, especially following Twitter’s decision to drop the format from their Streaming API in favor of JSON. I won’t get into that debate here, but my original intention had been to use the XML feed and transform it to HTML using XSLT. That became a little too convoluted–primarily because links within a tweet must be resolved using regular expressions. That would have been possible using XSLT 2.0 but, unfortunately, PHP’s libxslt only supports XSLT 1.0. I therefore choose JSON; it’s a less-verbose format and can be decoded by PHP’s json_decode() function.

      The TwitterStatus Class

      The widget functionality is wrapped in a single class named TwitterStatus (refer to the twitter/twitterstatus.php file in the download). Seven public and one private property is defined:
      class TwitterStatus
      	public $ID;				// twitter user name
      	public $Count;			// tweets to fetch
      	public $WidgetTemplate;	// widget template
      	public $TweetTemplate;	// template for each tweet
      	public $ParseLinks;		// parse links in Twitter status
      	public $DateFormat;		// PHP or "friendly" dates
      	public $CacheFor;		// number of seconds to cache feed
      	private $cache;			// location of cache files
      note: Public and Private?
      If you’re new to Object-Orientated Programming, a public property (variable) or method (function) can be accessed from outside the class, i.e. we can set and examine the $ID value from any code no matter where it resides. A private property or method has local scope and only be used within the class itself. The $cache property can be set and examined within the TwitterStatus class, but it’s not visible elsewhere. PHP also provides protected properties and methods. We’re not using those here, but protected members are visible within the class and to inherited and parent classes.
      We now require a constructor function which runs when a new TwitterStatus object is created. Our constructor simply sets each property to a default value:
      // constructor
      public function __construct($id = null, $count = 0) {
      	// constants
      	$this->cache = __DIR__ . '/cache/';	// cache location
      	$this->CacheFor = 900;				// cache feed for 15 minutes
      	$this->ID = $id;
      	$this->Count = $count;
      	$this->ParseLinks = true;
      	$this->DateFormat = 'friendly';
      	// default widget template
      	$this->WidgetTemplate =
      		'<div class="twitterstatus">' .
      		'<h2><a href="{screen_name}"><img src="{profile_image_url}" width="24" height="24" alt="{name}" />{name}</a></h2>' .
      		'<ul>{TWEETS}</ul>' .
      	// default tweet template
      	$this->TweetTemplate =
      		'<li>{text} <em>{created_at}</em></li>';
      The only private property is $cache–the directory where we’ll store cached versions of the widget so we’re not interrogating the Twitter API during every page load. It’s set to the directory named ‘cache’ within the directory where twitterstatus.php resides–it’ll need to have appropriate read/write permissions set. The $ID and $Count properties can be set when a TwitterStatus object is instantiated, e.g.,
      $t = new TwitterStatus('sitepointdotcom', 10);
      or we can change the properties separately, e.g.,
      $t = new TwitterStatus();
      $t->ID = 'sitepointdotcom';
      $t->Count = 10;
      If $ParseLinks is set to true, our code will translate links within the tweet to HTML anchor tags. $DateFormat can be set to a PHP date() format, e.g.
      $t->DateFormat = 'g:ia j F Y'; // 1:15pm 27 January 2011
      Alternatively, $DateFormat can be set to “friendly” (the default string) to indicate we want friendly dates (ten minutes ago, yesterday, last week, etc.) Finally, we set two HTML templates:
      • $WidgetTemplate is the widget’s outer HTML. The {TWEETS} code indicates where one or more $TweetTemplate blocks will appear.
      • $TweetTemplate is the HTML for an individual tweet.
      Either property can include {named-values}
      from the Twitter feed, e.g. {text}, {source}, {name}, {location}, {profile_image_url}, {statuses_count} etc. It’s easiest to view the XML version of the feed to locate named values. The developer can therefore specify their own widget HTML, e.g.,
      $t->WidgetTemplate =
      	'<div>' .
      	'<img src="{profile_image_url}" />' .
      	'<ul>{TWEETS}</ul>' .
      $t->TweetTemplate =
      	'<li>Tweet {statuses_count}: {text} {created_at}</li>';

      Fetching the Twitter Feed

      We can now implement a private method to fetch the Twitter status data using PHP’s Client URL (cURL) library:
      private function FetchFeed() {
      	$r = '';
      	if ($this->ID != '' && $this->Count > 0) {
      		// fetch feed
      		$c = curl_init();
      		curl_setopt_array($c, array(
      			CURLOPT_URL => '' . $this->ID . '.json?count=' . $this->Count,
      			CURLOPT_HEADER => false,
      			CURLOPT_TIMEOUT => 10,
      		$r = curl_exec($c);
      	// return JSON as array
      	return (!!$r ? json_decode($r, true) : false);
      A number of cURL options are set, but the most important is the timeout. We’re allowing ten seconds for a Twitter response and, if that’s exceeded, PHP will give up and the function will return false. If everything works as expected, the result is parsed using json_decode() which returns an array of associative arrays matching the JSON data. We’ve covered a lot of ground today so it’s time for a break. In the next post, we’ll examine the code which transforms Twitter data into HTML code.

      Frequently Asked Questions about Creating Your Own Twitter Widget

      How can I customize the appearance of my Twitter widget?

      Customizing the appearance of your Twitter widget can be done through the use of CSS. You can change the color, size, and font of the tweets displayed in your widget. You can also add borders, backgrounds, and other design elements to make your widget stand out. To do this, you need to add the CSS code to your website’s stylesheet. If you’re not familiar with CSS, there are many online tutorials and resources available to help you learn.

      Can I display tweets from multiple accounts in my widget?

      Yes, you can display tweets from multiple accounts in your widget. You just need to add the Twitter handles of the accounts you want to display in the widget code. This can be useful if you want to display tweets from different departments of your company or from different members of your team.

      How can I filter the tweets displayed in my widget?

      You can filter the tweets displayed in your widget by using the ‘data-screen-name’ attribute in the widget code. This allows you to specify the Twitter account whose tweets you want to display. You can also use the ‘data-search’ attribute to display tweets that contain specific keywords or hashtags.

      Can I embed my Twitter widget on multiple pages of my website?

      Yes, you can embed your Twitter widget on multiple pages of your website. You just need to copy and paste the widget code into the HTML of each page where you want the widget to appear. This can be useful if you want to display your Twitter feed on your homepage, blog, and other pages of your website.

      How can I make my Twitter widget responsive?

      Making your Twitter widget responsive can be done by adding the ‘data-width’ and ‘data-height’ attributes to the widget code. These attributes allow you to specify the width and height of the widget, which will automatically adjust to fit the screen size of the device used to view your website.

      Can I display images and videos in my Twitter widget?

      Yes, you can display images and videos in your Twitter widget. The ‘data-cards’ attribute in the widget code allows you to enable or disable the display of images and videos in the tweets. By default, this attribute is set to ‘true’, which means images and videos will be displayed.

      How can I update the tweets displayed in my widget?

      The tweets displayed in your Twitter widget are automatically updated every time a new tweet is posted on the Twitter account specified in the widget code. You don’t need to manually update the widget to display the latest tweets.

      Can I display retweets and replies in my Twitter widget?

      Yes, you can display retweets and replies in your Twitter widget. The ‘data-show-replies’ attribute in the widget code allows you to enable or disable the display of retweets and replies in the tweets. By default, this attribute is set to ‘false’, which means retweets and replies will not be displayed.

      How can I add a follow button to my Twitter widget?

      Adding a follow button to your Twitter widget can be done by adding the ‘data-show-follow-button’ attribute to the widget code. This attribute allows you to enable or disable the display of the follow button, which allows users to follow the Twitter account directly from the widget.

      Can I display the tweet timestamp in my Twitter widget?

      Yes, you can display the tweet timestamp in your Twitter widget. The ‘data-show-timestamp’ attribute in the widget code allows you to enable or disable the display of the tweet timestamp, which shows the date and time when the tweet was posted.

      Craig BucklerCraig Buckler
      View Author

      Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

      Share this article
      Read Next
      Get the freshest news and resources for developers, designers and digital creators in your inbox each week