Display Twitter Feed on Website Using PHP

Previously, we learned how to display an Instagram feed on your website using PHP.

Today, this tutorial will help you learn how to display a Twitter feed on your website using PHP. Twitter is a powerful tool for businesses and individuals looking to promote their brands or products.

If you're running a website for your brand, it makes sense to incorporate your Twitter feed into your website. This allows your followers to stay updated with your latest tweets without ever having to leave your site.

However, the standard Twitter widget may not always be the best fit for your website's design. That's why we'll show you how to customize the look and feel of your Twitter feed to match your website's design scheme.

You'll learn how to retrieve tweets, format them, and display them on your website using PHP. So, whether you're a developer or just looking to add this feature to your website, this tutorial is for you.

Don't want to code?

Before we start coding, you might be someone not really interested in coding. Or, you just want a quick solution to adding a Twitter feed to your website.

If that's the case, you need to use a "no code" approach. One way of doing it is to use a website plugin called SociableKIT. It is a free website plugin that allows you to embed your Twitter feed on your website. No coding is required.

Let's go back to coding below.

Source Code Overview

Here’s an overview of what our code does:

  1. It gets a Twitter users' profile information and posts from a specified Twitter account. We'll try Taylor Swift's Twitter account in the demo.
  2. Display these Twitter data on a webpage (assuming it is your WordPress or PHP website.)
  3. Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this excellent front-end framework, see our step by step Bootstrap tutorial here.

Final output

We have to know where we are going. If we're done with the code tutorial in this post, we will achieve this output:


Obtain Access Tokens and Keys

Go to Twitter Apps page.

Click the 'Create New App' button on the upper right corner.

Fill out the form with your information

Go back to the twitter apps page, you should see your new app now

Click your app and go to the "Keys and Access Tokens" tab


There you will see the access tokens and keys you need:

  • Consumer Key (API Key)
  • Consumer Secret (API Secret)
  • Access Token
  • Access Token Secret

Create The index.php File

We will make index.php Bootstrap ready. For those not familiar with the CSS framework Bootstrap, please refer to our step-by-step tutorial here: Step by Step Bootstrap Tutorial for Beginners

The index.php file will have the following code.

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Display Twitter Feed On Website - LEVEL 2 - Live Demo</title>
        <!-- Bootstrap CSS -->
    <link href="libs/js/bootstrap/dist/css/bootstrap.css" rel="stylesheet" media="screen">
<!-- jQuery library -->
<script src="libs/js/jquery.js"></script>
<!-- bootstrap JavaScript -->
<script src="libs/js/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="libs/js/bootstrap/docs-assets/js/holder.js"></script>
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>

Put Container Tags, Page Title and HTML

We will have the following code inside the "body" tag of our code in section 4.0

<div class="container">
    <div class="col-lg-12">
        <div class="page-header">
            <h1>Display Twitter Feed On Website - LEVEL 1 - Live Demo</h1>
    <div class="col-lg-4">
    </div> <!-- end <div class="col-lg-4"> -->
    <div class="col-lg-8">
    </div> <!-- end <div class="col-lg-8"> -->
</div> <!-- end <div class="container"> -->

Specify Keys And Variable Values

The following code will be inside the DIV tag with class="col-lg-4".

Access token and keys value were retrieved during our section 3.0 earlier.

// keys from your app
$oauth_access_token = "change_to_your_oauth_access_token ";
$oauth_access_token_secret = "change_to_your_oauth_access_token_secret ";
$consumer_key = "change_to_your_consumer_key ";
$consumer_secret = "change_to_your_consumer_secret ";
// we are going to use "user_timeline"
$twitter_timeline = "user_timeline";
// specify number of tweets to be shown and twitter username
// for example, we want to show 20 of Taylor Swift's twitter posts
$request = array(
    'count' => '10',
    'screen_name' => 'taylorswift13'

Get OAuth Signature

OAuth is an authentication protocol that allows users to approve application to act on their behalf without sharing their password. More about Twitter OAuth here.

Put the following code below our code on section 6.0

// put oauth values in one oauth array variable
$oauth = array(
    'oauth_consumer_key' => $consumer_key,
    'oauth_nonce' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_token' => $oauth_access_token,
    'oauth_timestamp' => time(),
    'oauth_version' => '1.0'
// combine request and oauth in one array
$oauth = array_merge($oauth, $request);
// make base string
$r = array();
foreach($params as $key=>$value){
    $r[] = "$key=" . rawurlencode($value);
$base_info = $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
// get oauth signature
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;

Make The Authorization Request

We can now make request to the Twitter API with the help of $oauth variable and cURL.

Put the follwing code below our code on section 7.0

// make request
// make auth header
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value){
    $values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
// get auth header
$header = array($r, 'Expect:');
// set cURL options
$options = array(
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_HEADER => false,
    CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),

Retrieve Twitter Feeds With User Information

Using the the following code, we can get the data in JSON format. Put it below our code on section 8.0

// retrieve the twitter feed
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
// decode json format tweets
$tweets=json_decode($json, true);

Display Twitter User Information

The following code shows how we can display the specified Twitter user's information. Put it below our code on section 9.0

// show user information
echo "<div class='overflow-hidden'>";
    // user data
    $profile_photo=str_replace("normal", "400x400", $tweets[0]['user']['profile_image_url_https']);
    // show profile photo
    echo "<img src='{$profile_photo}' class='img-thumbnail' />";
    // show other information about the user
    echo "<div class='text-align-center'>";
        echo "<div><h2>{$name}</h2></div>";
        echo "<div><a href='https://twitter.com/{$screen_name}' target='_blank'>@{$screen_name}</a></div>";
    echo "</div>";
    echo "<hr />";
echo "</div>";

Display Twitter User Status Count And Follower Count

Now we will put the following code inside the DIV tag with class="col-lg-8".

// show numbers
echo "<div class='overflow-hidden'>";
    // show number of tweets
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Tweets</div>";
        echo "<div class='badge font-size-20px'>" . number_format($statuses_count, 0, '.', ',') . "</div>";
    echo "</div>";
    // show number of followers
    echo "<div class='float-left margin-right-2em text-align-center'>";
        echo "<div class='color-gray'>Followers</div>";
        echo "<div class='badge font-size-20px'>" . number_format($followers_count, 0, '.', ',') . "</div>";
    echo "</div>";
echo "</div>";
echo "<hr />";

Display Twitter Posts / Status Feed

Finally we can now display the user's Twitter posts.

// show tweets
foreach($tweets as $tweet){
    // show a tweet
    echo "<div class='overflow-hidden'>";
        // show picture
        echo "<div class='tweet-image'>";
            echo "<img src='{$profile_photo}' class='img-thumbnail' />";
        echo "</div>";
        // show tweet content
        echo "<div class='tweet-text'>";
            // show name and screen name
            echo "<h4 class='margin-top-4px'>";
                echo "<a href='https://twitter.com/{$screen_name}'>{$name}</a> ";
                echo "<span class='color-gray'>@{$screen_name}</span>";
            echo "</h4>";
            // show tweet text
            echo "<div class='margin-zero'>";
                // get tweet text
                // make links clickable
                $tweet_text=preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $tweet_text);
                // output
                echo $tweet_text;
            echo "</div>";
        echo "</div>";
    echo "</div>";
    echo "<hr />";

Add Your Custom Styling

The following CSS code is what I used to add a some style on our page. I put it inside the "head" tag, just below the Bootstrap CSS.

<!-- custom CSS -->
    margin:0 1em 0 0;
    float:left; width:15%;
.tweet-image img{
    float:left; width:80%;

Control Background and Link Colors

You can control or change the background or link colors by going to the design settings section of your Twitter account.

Here's how you can go to that page:

  1. Go to twitter.com.
  2. On the upper right corner of the page, click your picture.
  3. Click "Settings" in the dropdown.
  4. On the left sidebar, click "Design."

You should see the following page.


"Theme Color" is the link color.

Source code or SociableKIT?

You can choose whether to download our source code or use the SociableKIT Twitter feed widget.

Show Twitter users’ profile pictureβœ”βœ”
Show Twitter users’ nameβœ”βœ”
Show Twitter users’ usernames with linkβœ”βœ”
Show the number of tweetsβœ”βœ”
Show exact number of followersβœ”βœ”
Specify number of tweets to displayβœ”βœ”
Specify Twitter username where to get tweetsβœ”βœ”
Show profile pic in tweetsβœ”βœ”
Show profile name in tweetsβœ”βœ”
Show profile username in tweetsβœ”βœ”
Show original tweetsβœ”βœ”
Show retweetsβœ”βœ”
Links in tweets are clickableβœ”βœ”
Responsive, mobile-friendly layoutβœ”βœ”
No coding required-βœ”
Works with any website builders like WordPress, Squarespace, or Wix-βœ”
Customize colors, font, and more-βœ”
Priority chat and email support-βœ”
Lifetime support and system updates-βœ”
No need to worry about Twitter API updates-βœ”
Use the buttons below. ↓CodeSociableKIT

What's Next?

Congratulations! You completed our series! For now, that is all for our social media API tutorial series.

You may want to explore a different tutorial series. Please select from our web development tutorials.

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

β˜…β˜…β˜…β˜…β˜… β€œWow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

β˜…β˜…β˜…β˜…β˜… β€œThe fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

β˜…β˜…β˜…β˜…β˜… β€œThanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

β˜…β˜…β˜…β˜…β˜… β€œHey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

β˜…β˜…β˜…β˜…β˜… β€œWords can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful Display Twitter Feed on Website Using PHP Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our Display Twitter Feed on Website Using PHP helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about Display Twitter Feed on Website Using PHP

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!