Saturday, July 2, 2022

Web Developer Class: Building a Twitter Feed with PHP

In today’s world of social networking there will come a time that someone asks you to do Twitter integration for their website. What makes this a little difficult sometimes is the wide range of Twitter “apps” out there, that all do different things but at the end of the day
leave you very little power in terms of styling and presentation. Because I have an utter dislike of anything copied from someone else, I have
decided to show you a very simple way for you to get ANY Twitter feed from Twitter and display it on your website.

What is important to note here is that at this point we are not updating Twitter – that would usually require an App, something we might
get to at another time. What we are doing here rather is simply extracting data from Twitter via it’s RSS Feed – something which is actually
ridiculously simple to do.

With that out the way, let’s get started.

A few things to note

There are a few things that could annoy you as you develop this little function. Firstly, Twitter only allows 150 requests from a specific host
per hour. Since you will most likely be working on localhost, and since there are probably a few thousand feeds being drawn by people testing from
localhost, it is likely that you will not get back any result because Twitter would have blocked it very quickly. A simple way to get around this is to
upload your code to your hosting account and test it from there. Another repercussion of this is that if you have a rather busy website, your 150 requests
per hour could be used up rather quickly, meaning that for the rest of that hour users are going to see an error message instead of a Twitter feed. I usually
get around this by running a cron to update the Twitter feed every 30 minutes, and then chucking that feed in the database. In that way we not only cut out slow pageloads while our server reads the Twitter feed (which could take almost a minute on a slow connection), but we also make sure that we are only doing two extractions of data per hour, making the site faster and more user friendly – not to mention saving on bandwidth.

Throughout this article we will be talking about Twitter ID’s. To get a Twitter ID is very simple. Simply go to your Twitter page and look at the bottom
right of the page, you will see a little RSS icon. Click on it, and you will be taken to a URL like: The last part, which is all digits, is the Twitter ID (19058681 in this case).

Please do note that this article assumes some proficiency in simple OOP operations, as well as database interaction (which is not covered here due to the
scope of the article)

The demo of this application can be downloaded HERE

The Twitter Class

Popular Articles