How to Retrieve Twitter Timeline and Hashtags in Php

How to Retrieve Twitter Timeline and Hashtags in PHP
by Janeth Kent Date: 12-07-2013 twitter php programming development hashtag OAuth API

How to Retrieve Twitter Timeline and Hashtags in PHP (Twitter OAuth API 1.1)

So, here we offer a guide that explains how to retrieve user timeline and hashtag with Twitter REST API 1.1.

Before we start, we need:

  • You need to create an application.
  • Now, you need to get your consumer key, consumer secret, access token and access token secret.
  • We use a Twitter Library called CodeBird-PHP.
  • To make all the tweets we retrieve pretty, we will be using Grid-A-Licious



Since all HTML Markup will be generated by jQuery, we only need a div with an id called#jstwitter

<div id="jstwitter"></div>
<div class="item">
<div class="tweet-wrapper">
<span class="text">{TEXT}</span>
<span class="time">
<a href="{URL}" target="_blank">{AGO}</a>
<span class="user">{USER}</span>


We are going to create a Pinterest style with Grid-A-Licious.

#jstwitter {
position: relative;
#jstwitter .item {
-webkit-box-shadow:0 0 3px 1px rgba(100,100,100,0.2);
-moz-box-shadow:0 0 3px 1px rgba(100,100,100,0.2);
box-shadow:0 0 3px 1px rgba(100,100,100,0.2);
background: #fff;
#jstwitter .tweet-wrapper {
#jstwitter .item a {
text-decoration: none;
color: #03a8e5;
#jstwitter .item img {
#jstwitter .item a:hover {
text-decoration: underline;
#jstwitter .item .text {
#jstwitter .item .time, #jstwitter .tweet .user {
font-style: italic;
color: #666666;


We're not going to write our own PHP OAuth authentication, we will be using a Twitter Library called CodeBird-PHP (CodeBird Documentation)

//We use already made Twitter OAuth library
require_once ('codebird.php');
//Twitter OAuth Settings
$CONSUMER_KEY = '...';
$ACCESS_TOKEN = '...';
//Get authenticated
Codebird::setConsumerKey($CONSUMER_KEY, $CONSUMER_SECRET);
$cb = Codebird::getInstance();
//retrieve posts
$q = $_POST['q'];
$count = $_POST['count'];
$api = $_POST['api'];
$params = array(
'screen_name' => $q,
'q' => $q,
'count' => $count
//Make the REST call
$data = (array) $cb->$api($params);
//Output result in JSON, getting it ready for jQuery to process
echo json_encode($data);

The Javascript / jQuery

Depend on the parameters, you can either search for hashtag, or load a user timeline. The script sends the parameters to the PHP file, and PHP script gets us authenticated, and PHP returns Twitter data in JSON format. The following scripts read the data and parse them in to HTML markup.

For more information about the Twitter Object, you can read it here.

User Timeline Search Tweets
$(function() {        
// Set twitter hash/user, number of tweets & id/class to append tweets
// You need to clear tweet-date.txt before toggle between hash and user
// for multiple hashtags, you can separate the hashtag with OR, eg:
// hash: '%23jquery OR %23css'            
search: '%23heroes2013', //leave this blank if you want to show user's tweet
user: 'quenesstestacc', //username
numTweets: 21, //number of tweets
appendTo: '#jstwitter',
useGridalicious: true,
template: '<div class="item">{IMG}<div class="tweet-wrapper"><span class="text">{TEXT}</span>\
<span class="time"><a href="{URL}" target="_blank">{AGO}</a></span>\
by <span class="user">{USER}</span></div></div>',
// core function of jqtweet
loadTweets: function() {
var request;
// different JSON request {hash|user}
if ( {
request = {
count: JQTWEET.numTweets,
api: 'search_tweets'
} else {
request = {
q: JQTWEET.user,
count: JQTWEET.numTweets,
api: 'statuses_userTimeline'
url: 'grabtweets.php',
type: 'POST',
dataType: 'json',
data: request,
success: function(data, textStatus, xhr) {
     if (data.httpstatus == 200) {
         if ( data = data.statuses;
var text, name, img;    
try {
// append tweets into page
for (var i = 0; i < JQTWEET.numTweets; i++) {        
img = '';
url = '' + data[i].user.screen_name + '/status/' + data[i].id_str;
try {
if (data[i].entities['media']) {
img = '<a href="' + url + '" target="_blank"><img src="' + data[i].entities['media'][0].media_url + '" /></a>';
} catch (e) {
//no media
$(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) )
.replace('{USER}', data[i].user.screen_name)
.replace('{IMG}', img)
.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) )
.replace('{URL}', url )            
} catch (e) {
//item is less than item count
     if (JQTWEET.useGridalicious) {
     //run grid-a-licious
                gutter: 13,
                width: 200,
                animate: true
} else alert('no data returned');
* relative time calculator FROM TWITTER
* @param {string} twitter date string returned from Twitter API
* @return {string} relative time like "2 minutes ago"
timeAgo: function(dateString) {
var rightNow = new Date();
var then = new Date(dateString);
if ($.browser.msie) {
// IE can't parse these crazy Ruby dates
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
var diff = rightNow - then;
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
if (isNaN(diff) || diff < 0) {
return ""; // return blank string if unknown
if (diff < second * 2) {
// within 2 seconds
return "right now";
if (diff < minute) {
return Math.floor(diff / second) + " seconds ago";
if (diff < minute * 2) {
return "about 1 minute ago";
if (diff < hour) {
return Math.floor(diff / minute) + " minutes ago";
if (diff < hour * 2) {
return "about 1 hour ago";
if (diff < day) {
return Math.floor(diff / hour) + " hours ago";
if (diff > day && diff < day * 2) {
return "yesterday";
if (diff < day * 365) {
return Math.floor(diff / day) + " days ago";
else {
return "over a year ago";
}, // timeAgo()
ify: {
link: function(tweet) {
return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
var http = m2.match(/w/) ? 'http://' : '';
return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
at: function(tweet) {
return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
return '<a target="_blank" class="twtr-atreply" href="' + username + '">@' + username + '</a>';
list: function(tweet) {
return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
return '<a target="_blank" class="twtr-atreply" href="' + userlist + '">@' + userlist + '</a>';
hash: function(tweet) {
return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
return before + '<a target="_blank" class="twtr-hashtag" href="' + hash + '">#' + hash + '</a>';
clean: function(tweet) {
return this.hash(;
} // ify

And finally, you run the script like this:

$(function () {
// start jqtweet!


by Janeth Kent Date: 12-07-2013 twitter php programming development hashtag OAuth API hits : 10246  
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.


Related Posts

Validating HTML forms using BULMA and vanilla JavaScript

Today we are going to write about contact forms and how to validate them using JavaScript. The contact form seems to be one of the top features of every basic home…

The State of PHP 8: new features and changes

PHP 8.0 has been released last November 26: let's discover together the main innovations that the new version introduces in this language. PHP is one of the most popular programming languages…

Django vs. Laravel: Market Share Comparison

There are two leading frameworks in the web development segment: Django and Laravel. In this article, we prepared a Django and Laravel comparison focusing on their market share so that…

How to make the website's dark mode persistent with Local Storage, CSS and JS

Recently we wrote about how to do a switchable alternative color mode or theme, a very useful and popular feature to websites. Today’s article is going to be about how…

A Java approach: While loop

Hello everyone and welcome back! After having made a short, but full-bodied, introduction about cycles, today we are finally going to see the first implementations that use what we have called…

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

A Java approach: The Cycles - Introduction

Hello everyone and welcome back! Until now, we have been talking about variables and selection structures, going to consider some of the fundamental aspects of these two concepts. Theoretically, to…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

A Java approach: boolean variables

The previous time, we talked extensively about Boolean variables, trying to outline the main operations that can be carried out at a practical level.  Of all the cases examined, we have…

Why You Should Hire Node.js Developer for Your Backend Development

When developers are building a new website, they mainly focus on both frontend and backend development. The frontend code helps create the interfaces through which the app interacts with the…

A Java approach: condtional structures

Hello everyone and welcome back! The previous times we have introduced the concept of variable, trying to define some basic concepts about it.  However, some situations suggest that the concept of…

Hashmap: Overflow Lists

In this short series of articles we will go to see how it is possible to create the Hashmap data structure in C. In the implementation we're going to use the…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration