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 Bearer Token

Go to Twitter Apps page.

Click the 'Add App' button.

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 Bearer Token you need:

  • Bearer Token

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.

	$tweets = [];
	$bio = [];
    // max tweet results when retrieving tweets
    $max_results = "5";

	// get profile username
    $username=isset($_GET['username']) ? $_GET['username'] : "SociableKIT_hq";
    // data to be retrieve when retrieving profile bio
	$bio_fields = 'user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,url,username,verified,withheld&expansions=pinned_tweet_id';

    // data to be retrieve when retrieving tweets
    $tweet_fields = 'tweet.fields=attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids,entities,geo,id,in_reply_to_user_id,lang,note_tweet,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld&expansions=attachments.media_keys,referenced_tweets.id&media.fields=duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width,alt_text';

    // bio data url
    $bioUrl = "https://api.twitter.com/2/users/by/username/".$username."?".$bio_fields;
	// tweets url
    $tweetsUrl = "";
    // bearer token from your app
	$bearerToken = "YOUR_BEARER_TOKEN";

Make The Authorization Request For the Bio

We can now make request to the Twitter API with the bearer token from your app using cURL.

The code below will allow us to retrieve the bio information.

Put the follwing code below our code on section 5.0

    // request header to be use, the bearer token will be use here.
    $headers = array(
        'Authorization: Bearer ' . $bearerToken

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $bioUrl);

    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // check if request is successful
    if ($httpcode >= 200 && $httpcode < 300) {
        $original_response = json_decode($response, true);

        // store the bio data retrieve from API to the $bio variable
        $bio = $original_response['data'];
		$profile_id = isset($bio['id']) ? $bio['id'] : "";
		$tweetsUrl = 'https://api.twitter.com/2/users/' . $profile_id . '/tweets?' . $tweet_fields . '&max_results=' . $max_results;
    } else {
        echo 'Error: HTTP ' . $httpcode;

Make The Authorization Request For the Tweets

We can now make request to the Twitter API with the bearer token from your app using cURL.

The code below will allow us to retrieve the tweets.

Put the follwing code below our code on section 6.0

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $tweetsUrl);

    $response = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($httpcode >= 200 && $httpcode < 300) {
        $original_response = json_decode($response, true);
        // store the tweets data retrieve from API to the $tweets variable
        $tweets = $original_response['data'];
    } else {
        echo 'Error: HTTP ' . $httpcode;

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

	echo "<div class='col-lg-4' style='margin-top:-13.5em;'>";

	// show user information
	echo "<div class='overflow-hidden bio-container'>";

		// user data
		$profile_photo = isset($bio['profile_image_url']) ? $bio['profile_image_url'] : "";
		$name = isset($bio['name']) ? $bio['name'] : "";
		$screen_name = isset($bio['username']) ? $bio['username'] : "";
		$location = "";
		$description = isset($bio['description']) ? $bio['description'] : "";
		$url = isset($bio['url']) ? $bio['url'] : "";
		$display_url = isset($bio['url']) ? $bio['url'] : "";
		$verified = isset($bio['verified']) ? $bio['verified'] : "";

		// 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>{$location}</div>";
			echo "<div>{$description}</div>";
			echo "<div><a href='{$url}' target='_blank'>{$display_url}</a></div>";
		echo "</div>";

		echo "<hr />";
	echo "</div>";

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
					$date = new DateTime($tweet['created_at']);
					$created_at = $utils->getTimeAgo($date->format('F j, Y'));


					// make links clickable
					$tweet_text=preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1" target="_blank">$1</a>', $tweet_text);

					// make users clickable
					$tweet_text = preg_replace('/@(\w+)/', '<a href="https://twitter.com/$1" target="_blank">@$1</a>', $tweet_text);

					// make hashtags clickable
					$tweet_text=preg_replace('/\#([a-z0-9]+)/i', '<a href="https://twitter.com/search?q=%23$1" target="_blank">#$1</a>', $tweet_text);

					// output
					echo $tweet_text;
					echo "<div class='color-gray'>{$created_at}</div>";

				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!

Hi! I'm Mike Dalisay, the co-founder of codeofaninja.com, a site that helps you build web applications with PHP and JavaScript. Need support? Comment below or contact [email protected]

I'm also passionate about technology and enjoy sharing my experience and learnings online. Connect with me on LinkedIn, Twitter, Facebook, and Instagram.