Build Your First Twitter App Using PHP in 8 Easy Steps



In my last article I explained the steps involved in setting up a developers account at Twitter and registering your first app- making this as easy as possible. Well, it’s time to get your hands dirty and actually build that app!

If you’re not a developer, don’t worry- I plan to make this as easy as possible. I passionately believe everyone should have the chance to play with this stuff and free their data.

I do make a few assumptions, however- you’ll have a website and be able to upload files to it (preferably via FTP) and your website should have the server side language PHP running. If you have a WordPress website then the answer to these questions should be yes. If this isn’t the case, then I hope there is something you can still learn from this article.


1. Create Your First PHP File

I don’t know what you use to edit text files on your computer. You might use Notepad or Text Edit or something similar. I used to use Notepad++ or Dreamweaver but now use SublimeText. It doesn’t matter, just load it up- we’re going to write our first script and upload it on to your website. Usually, web pages are just sent from your website’s servers as plain old HTML (the language used for web pages). However, servers can do some magical things before they get sent out by using server side languages. We’ll be using PHP since it’s probably the most popular.

We need to initiate PHP in the file so that your server knows what is coming is PHP and not plain old HTML. Firstly we’ll give the file name the PHP extension “.php” as opposed to the standard “.html” one. We also need to tell the server when to start and stop reading as PHP. To do this we need to use opening and closing PHP tags like this:

<?php
?>

Anything that goes in between these tags is seen as PHP. That’s where the magic starts. I’m not going to give a beginners tutorial on PHP here, because there are plenty examples on the web- including  a simple PHP intro on the PHP website and an introduction to PHP course on Udemy. For now, let’s do something really simple, and output some text. To do this we will use the “echo” statement in PHP. We put the text in double quotes and we end the line with a semi-colon (PHP throws a toddler’s tantrum if you forget to end a line with a semi-colon!).

<?php
echo "<h2>Simple Twitter API Test</h2>";
?>

Now, upload this up to your website. I’d recommend creating a folder or directory called something like “test“. This is particularly important if your website runs WordPress as we don’t want these files to get mixed up with your WordPress ones. Call the file littleApp.php and upload it. You can see my example here. It’s not very exciting… not yet anyway!


2. Use a PHP Wrapper Script

Don’t worry if you have no idea what a PHP Wrapper Script is. I am not sure I do either, but all will be revealed…

As I said in my previous article, an API (short for Application Programming Interface) is a system that allows other applications to talk to an application- receive information from it and send information to it. Twitter has had an API since 2006 (not long after it started). Initially it was very easy for developers to use. However, over the years, that API has become more sophisticated and in June 2013, Twitter (in version 1.1 of its API) have forced all applications interacting with its API to authenticate themselves. Authentication basically means that if you want to connect to the API, you have to say who they are and to prove that you have the authority to access the data for that particular user.

The reason for forcing you to authenticate is because Twitter wants to control access to their data. This is partly for creating a more unformed experience for end users, but also because they want to gain revenue from advertising and so need a strict control over the use of their data.

I hate when things are made difficult, so I was extremely glad when I came across an easy to understand article on the developers’ forum, Stack Overflow on how retrieve data from Twitter using v1.1 of their API. The accepted answer to the Stack Overflow question was written by a developer called James Mallison (J7mbo) who has gone out of his way to explain how to do this. A big thanks to him- as it is the reason this article is being written and also how my Twitter app, Twools (more about that later on), has been built.

Please Note It’s best to run this on a web server (i.e. not locally) and you may need to check a few things with your host first. Firstly make sure you have a modern version of PHP. I have tested it using PHP 5.2 an above, but really your host should be using 5.4 or higher. You will also need to have cURL installed. Don’t worry about what this is- but the wrapper script requires this to connect to the Twitter API. Most hosting environments should have this as standard- check with your host. You may also want to check that your host has the latest root certificates installed for cURL as I’ve had reports of some hosting hosts not bothering to do this. If Twools doesn’t work, you’ll need to ask your host! Thanks to Tyler Hakes for looking further into this!

James has developed a simple “PHP Wrapper” for calls to Twitter’s API v1.1. With this wrapper, you can more easily make calls to the API and then interact with the data. You can view the file on this GitHib repository and download it from here.

githib-twitter-api

Once you’ve download the file, unzip it and upload the file ‘TwitterAPIExchange.php‘ to the same folder as your ‘littleApp.php‘ file. Now we really are ready to create some Twitter API magic using PHP. Are you ready? Let’s move on!


3. Enter Your Tokens

Now that you have the PHP Twitter Wrapper script in the same directory as your littleApp.php file, we can use it to help us access the Twitter API.

To do this, we need to include the Twitter wrapper script using the ‘require_once‘ function. Once we’ve done that, we need to set our access tokens by adding it to the $settings array (remove the “YOUR_OAUTH_” etc bits and replace with your tokens). Don’t worry too much about this for now- all you need to know is that the PHP wrapper will use these tokens to make the connection to the Twitter API. If you don’t have your app access tokens, then have a read of my article on How to Create a Twitter App in 8 Easy Steps.

require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

4. Decide what Call to Make!

Now we need to decide what information we want to request from Twitter. Do you want to get the tweets from your timeline? How about someone else’s? Perhaps the tweets from one of your Twitter lists? Or even do a Twitter search? Well, it’s all very easy- all you need to do is get the url from the Twitter API documentation. At first it can look a little daunting, so I’ve included a few here to get you started…

  • User Timeline: https://api.twitter.com/1.1/statuses/user_timeline.json
    All your tweets or the tweets of the user you specify.
  • Mentions: https://api.twitter.com/1.1/statuses/mentions_timeline.json
    All the tweets in which another Twitter user mentions you.
  • Home Timeline: https://api.twitter.com/1.1/statuses/home_timeline.json
    All the tweets from the people you follow
  • Twitter Search: https://api.twitter.com/1.1/search/tweets.json
    A Twitter search with the query you specify.

We need to give the PHP Twitter wrapper the URL so it can make the correct API request for us. In order to do this, we will need to create a string with the URL in it. Let’s call that string $url:

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

As well as the URL and your API tokens, Twitter sometimes needs a bit more information in order to proceed. That information depends on the Twitter resource you are requesting. If you don’t specify any other information with the user timeline request then it will return your tweets. However, you can tell the Twitter API to return the tweets of another user by sending their ID or screen name.


5. To GET or to POST

When want to visit a website, your browser makes a request to the website’s server. This type of request uses a way of connecting (or a “protocol”) called “Hyper Text Transfer Protocol” (or HTTP) which was first invented in the early 1990s by Tim Berners-Lee and his team. You don’t really need to know this, but I think it’s useful in understanding the different ways we can connect to the Twitter API. In HTTP we can request information in different ways.

The most popular one is “getting” information from a server using the “GET” method. With “GET” we request the information by sending the URL as well as other information. This other information can be added to the end of the URL by putting a question mark and stringing on the information after that. For example:

https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=iagdotme

We can also add more bits of information by using the ampersand symbol (“&”)…

https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=iagdotme&count=50

The other popular method is called “POST” and is normally used when you submit a form. Because stringing all the information contained in a form to the end of a URL wouldn’t be practical (just think how long the URL could be!), the extra information is sent separately to the URL.

There other methods which are used far less regularly- HEAD, OPTIONS, PUT, DELETE, TRACE and CONNECT– let’s not worry about those for now.

Twitter accepts both the GET and POST methods, but generally asks for read only data (such as getting tweets) to be requested by the GET method and for writing data (such as sending a tweet) be done by the POST method. There is one exception in that, if your request string is going to be very long, you might want to use POST even though you are requesting read only data. This is because the URL could end up being too long.

For this article, we are only going to be requesting information, so let’s stick with GET.

So we’ve given the Twitter wrapper our access tokens and the URL for the API call- now we need to tell it we want to use the GET method. To do this, we set another variable so that the PHP Twitter wrapper can make the correct request. Let’s call that string $requestMethod:

$requestMethod = "GET";

We also need to set the GET information too. We could append that to the URL, but for the PHP Twitter Wrapper, we are going to add that information separately. I recommend looking through each Twitter API resource in the documentation as each resource have different parameters you can add. For the user_timeline one, we could add screen_name and count. The screen_name parameter allows us to ask the Twitter API for the tweets from another user and the count parameter tells twitter how many results we want returned. In this case we want to receive the last 20 tweets from Twitter user, @iagdotme. In this case the GET string would be:

?username=iagdotme&count=20

In order to hand this over to the PHP Twitter wrapper, let’s set it in a string- $getString:

$getfield = '?screen_name=iagdotme&count=20';

Are you still following what I am saying? I hope so! Let’s move on…


6. Connect to the Twitter API

I hope you’re excited, because we’ve now reached the point when we can make that call to Twitter!

Let’s recap. We’ve…

  • Uploaded the PHP wrapper and your test PHP file to a directory/folder on your website
  • Included the PHP wrapper script at the start of your test PHP script
  • Set your access tokens in the $settings array
  • Set the URL for the API request
  • Set the HTTP method for the request as GET
  • Set the extra bits of information that Twitter needs for the request (screen name and count) in the $getfield String

Now we need to make the call using the PHP Twitter Wrapper. To do this and to output it, we evoke the TwitterAPIExchange class with the access tokens and give it all the extra bits of information ($getField, $url and $requestMethod)…

$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();

If you run this file from your browser, you’ll see the request from Twitter. It’s in a format called JSON. Don’t worry about that for now- the main thing is that we’ve got the information.

Here is the code we’ve got so far. Feel free, to copy, upload and run.

<?php
require_once('TwitterAPIExchange.php');

/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
    'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
    'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
    'consumer_key' => "YOUR_CONSUMER_KEY",
    'consumer_secret' => "YOUR_CONSUMER_SECRET"
);

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

$requestMethod = "GET";

$getfield = '?screen_name=iagdotme&count=20';

$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest();
?>

You can see an example of the output here (please note this is just a cache of the output, since I don’t want to make an API call each time someone views the file).


7. Do Stuff with the Data

So, we’ve now got the data from Twitter. But what do we do with it? It’s in this weird format called JSON! Well, some of you will have experience with JSON, but I know many of you won’t. The reason Twitter chooses this over other formats (such as XML and RSS) is that it can be easier to work with and it allows more of a rich data set. That’s definitely true- Twitter gives us lots of goodness in the JSON output, but it can be daunting at first.

Well, there is a PHP function which can come to our rescue called json_decode. It converts or decodes a JSON string into an object or an array. For this exercise we’re going to convert the JSON string into an “associative array”. An array is a special string that contains more than one value. In an associative array, you can give each value a name or key. This makes it easier to retrieve that value later. In our case, we can ask the array to give us the text of the tweet or the screen name. For more information, have a look at this simple article on arrays from W3 Schools.

So, instead of outputting the JSON string, lets convert it to an associative array using the json_decode function:

$string = json_decode($twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
             ->performRequest(),$assoc = TRUE);

You’ll notice that this is almost the same as before, except we’ve wrapped it with json_decode and set $assoc to TRUE so that we convert the JSON to an associative array.

We can’t just output an array using echo since it has more than one value. For now let’s output the array using the print_r function. To make it easier to read, we’ll wrap it in <pre> tags so that it is pre-formatted text (i.e. fixed width).

Just in case Twitter returns an error, it’s important to be notified of this. Twitter returns any errors in the error array, so we can check for that. If it exists, we can return the error message and stop the script:

if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}

Here is the full code so far…

<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
$getfield = '?screen_name=iagdotme&count=20';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
echo "<pre>";
print_r($string);
echo "</pre>";
?>

You can view an example of the output here.


8. Let’s go all Loopy!

Now that we’ve got our data the way we want it, we can start to access the information about each tweet. One way to do that is to loop round the array and asking for each bit of information. Since this is our user timeline data, we can ask it for:

  • created_at – Date and time of tweet
  • favorited – Whether the tweet was favorited or not.
  • id_str – The Id of the tweet
  • text – The text of the tweet
  • retweet_count – How many times the tweet was retweeted

and about the user who tweeted the tweet:

  • name – The name of the user
  • profile_image_url – the URL of the the user’s profile pic
  • created_at – When their account was created (when they first joined Twitter)
  • location – Their location (as set in their profile)
  • url – The link in their profile
  • name – Their full name (as listed in their profile)
  • listed_count – How many Twitter lists they are in.
  • followers_count – How many followers they have.
  • protected – Are their tweets protected?
  • statuses_count – How many tweets have they sent?
  • friends_count – How many people do they follow (friends)
  • screen_name – Their screen name.

That is not an exhaustive list- for all the entities, have a look at the Twitter documentation for user timelines.

For this exercise we’re going to loop round our associative array and output all the information. It’s not going to look pretty, but that’s not the point of this exercise.

PHP has a great little function to help us loop round an array. It is called foreach(). For our exercises we will use it like this:

foreach($string as $items)
    {
        // Do Stuff
    }

The foreach function loops through the array and each time sets $items to the current value. We can then do stuff with that value before the loop carries on. Because it is an associative array we can access the keys very easily using the keys that Twitter supplied (for example “text”, “created_at”, “location”). We can output the tweet information like this:

foreach($string as $items)
    {
        echo $items['created_at']."<br />";
        echo $items['text']."<br />";
    }

Information about the user who tweeted the tweet is stored in an array which we can access in the loop using $items[‘user’]. For example if we want their screen name, we’d use $items[‘user’][‘screen_name’]. Here is an expanded version of the above:

foreach($string as $items)
    {
        echo "Time and Date of Tweet: ".$items['created_at']."<br />";
        echo "Tweet: ". $items['text']."<br />";
        echo "Tweeted by: ". $items['user']['name']."<br />";
        echo "Screen name: ". $items['user']['screen_name']."<br />";
        echo "Followers: ". $items['user']['followers_count']."<br />";
        echo "Friends: ". $items['user']['friends_count']."<br />";
        echo "Listed: ". $items['user']['listed_count']."<br />";
    }

Now, to be a bit more cunning, why don’t we also allow you to show the tweets of another user? By adding the following line, we can check to see if you’ve added a string to the end of your URL (our little GET request!) to set a different screen name:

if (isset($_GET['user'])) {$user = $_GET['user'];} else {$user = "iagdotme";}

If you append ?user=your_screen_name to the url of your script, we can use that to set the screen name in our API request. If it is not set then it will use the default one (you’ll have to change “iagdotme” above to your screen name). As well as that, we’ll have to change another line in our script- the $getField string- so that we can set the user:

$getfield = "?screen_name=$user&count=$count";

Now, if you run the script as before, it will output your tweets. If you append ?user=lifehacker to the end of your URL, it will give you the tweets from @lifehacker.

Here is the full version of our script:

<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user']))  {$user = $_GET['user'];}  else {$user  = "iagdotme";}
if (isset($_GET['count'])) {$count = $_GET['count'];} else {$count = 20;}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
foreach($string as $items)
    {
        echo "Time and Date of Tweet: ".$items['created_at']."<br />";
        echo "Tweet: ". $items['text']."<br />";
        echo "Tweeted by: ". $items['user']['name']."<br />";
        echo "Screen name: ". $items['user']['screen_name']."<br />";
        echo "Followers: ". $items['user']['followers_count']."<br />";
        echo "Friends: ". $items['user']['friends_count']."<br />";
        echo "Listed: ". $items['user']['listed_count']."<br /><hr />";
    }
?>

You can view the output of this script, here. I have also added it as a github repository called “My First Twitter App“.

That’s all folks!

So that’s it. You’ve created your first Twitter app. OK, it’s not the most elegant or useful- but it is a start. We’re not going to end it all here, because in my next article I’ll be showing you my first app, Twools, and I am really excited about it.

A massive thanks to James Mallison who developed the PHP Twitter Wrapper script and took the time to explain things on Stack Exchange. I hope you’ve been able to start your journey in to the Twitter API world. Have fun!


Want in on the latest tools, tips, hacks & techniques?

Get the Seriously Social Newsletter for Free!

You will receive an email no more than once a week.


About Ian Anderson Gray

Ian is a speaker, coach, social media consultant, web developer & Partner of Select Performers. In real life he is a husband, dad and geek and is rather partial to tea, coffee & Indian cooking. Find out more



The Seriously Social Community

What do you think? Join the fun & Let me know below...

Leave a Reply

470 Comments on "Build Your First Twitter App Using PHP in 8 Easy Steps"

Notify of
avatar

Sort by:   newest | oldest | most voted
pvdbussche
Guest
pvdbussche
8 days 1 hour ago

Dear Ian,
followed the instructions but get following error:
Fatal error: Uncaught Exception: SSL certificate problem: unable to get local issuer certificate in C:\xampp\htdocs\…\TwitterAPIExchange.php:305
Stack trace: #0 C:\xampp\htdocs\..\twitter.php(39): TwitterAPIExchange->performRequest() #1 {main} thrown in C:\xampp\htdocs\…\TwitterAPIExchange.php on line 305
Twitter.php is the full version of the script from above in Php 5.6 language level.

KInd regrads, Patrick

falahgs
Guest
23 days 1 hour ago

thanks for this tutorial
it is great tutorial and it is help to learn about twitter api for my new application
many thanks

Antony Van der Mude
Guest
Antony Van der Mude
1 month 7 days ago

Thanks so much. I wanted to get tweets for analysis. You made it easy!

TC
Guest
TC
1 month 18 days ago

Thanks for this it is very useful. In the example, you get information from your tweets and then also your user details. What I was hoping to do was to get info on ‘your’ tweets, but then if the tweet has been re-tweeted, display user information about the re-tweeter. Are you able to assist with modifying the code to achieve this? Thanks in advance, and also for all the support you are providing in these comments, which is hugely useful.

Bel
Guest
1 month 30 days ago

Is it possible to create twitter account using API? If so, could anyone please give me links of some resources?

Shreyas
Guest
2 months 10 days ago

how to make ‘Tweeeted by’ clickable and so if user click on name how to make API call & show profile?…thnking you with anticipation

Steven Siahaan
Guest
2 months 21 days ago

How can i fix this ? My php version is 5.6.11. And i have installing cURL .
Thanks
Fatal error: Uncaught exception ‘Exception’ with message ‘SSL certificate problem: unable to get local issuer certificate’ in C:\xampp\htdocs\TA\Twitter\TwitterAPIExchange.php:305 Stack trace: #0 C:\xampp\htdocs\TA\Twitter\index.php(25): TwitterAPIExchange->performRequest() #1 {main} thrown in C:\xampp\htdocs\TA\Twitter\TwitterAPIExchange.php on line 305

Brajbhooshan Singh Tomar
Guest
Brajbhooshan Singh Tomar
2 months 30 days ago

This blog is very useful to me ……THANK YOU VERY MUCH

vijay gupta
Guest
vijay gupta
3 months 18 days ago

Hello,
I want to show popular videos of twitter using API in php.
Please any body can help me by provide code.
I followed many tutorials but not get working.

Thanks in Advance 🙂

Enis Behar
Guest
Enis Behar
4 months 4 days ago

Great tutorial, Thanks Ian 🙂

Chryssy
Guest
Chryssy
4 months 6 days ago

Are there minimum system requirements for this script to work?

I’m having issues with json_decode not working (as in, my script gets to the line where I have the decoding, but doesn’t execute anything past it, but the page doesn’t flat-out crash). After a lot of trouble shooting and trying new things, I decided to just copy-paste your full, complete script into a different php script and entered my tokens and keys. That is the ONLY thing I changed, but NOTHING displays when I try to load that php script.

My school’s server environment is pretty old, so I’m wondering if it doesn’t meet requirements to use json_decode.

Rey
Guest
Rey
5 months 5 days ago

thanks for this tutorial. its very informative.
but say I want to run a cronjob to store data to a database on a regular interval.
how do you handle twitter api rate limits?
any example would be greatly appreciated.
thanks and more power!

Fortune
Guest
Fortune
5 months 10 days ago

This is one of the best tutorials I’ve ever seen online. It deserves an AWARD! Thank you Ian. Can’t wait for the next article

LUIS AUGUSTO SILVA
Guest
LUIS AUGUSTO SILVA
5 months 21 days ago

Hi Ian! Congratulations of this article! I just make a suggestion…can you fix the article when you said about when Twitter register errors? Test if the string has an index errors before check its content…if (isset($string[ errors ])) { (your code) }. Hugs from Salvador Bahia Brazil and happy 2016!

Irfan
Guest
Irfan
6 months 12 days ago

Definitely it is helpful. but please write for signin/signup for users. Thanks a lot

Vinay Revu
Guest
Vinay Revu
6 months 17 days ago

Sir, I’m getting error as follows when implementing the above code.Thanks in advance….

Fatal error: Class ‘TwitterAPIExchange’ not found in /mywebsite/TwitterAPIExchange.php on line 23

Matt
Guest
5 months 24 days ago

you need to upload the PHP to your server.

Russell Lobo
Guest
Russell Lobo
6 months 30 days ago

Hi Ian,
This is gold.. Thanks a ton!!!
When is the post article coming up :)?

Ebuka
Guest
Ebuka
7 months 1 day ago

please i need to send bulk tweets what do i do

Muhammad Kashif
Guest
Muhammad Kashif
7 months 2 days ago

Hai,

I need some info about the twitter API from whom i retrieve all the upcoming events when i give the lat and long of the specific place. Is it possible?

Thanks

Joe
Guest
Joe
7 months 3 days ago

10/10 perfect guide, thanks man

Andy
Guest
Andy
7 months 6 days ago

Hi Ian,
Your app displays a filtered set of tweets in a different format than the one Twitter uses. I am confused about the Display requirements (https://about.twitter.com/company/display-requirements). Would that be ok to extract info from a tweet(at least directed to me) and arrange/present the way I like. Please comment.
Thanks, Andy.

guy
Guest
7 months 14 days ago

Hey Ian, can I reiterate the thanks? An immaculate instruction. Apologies if it’s already covered and I overlooked it, but can I send tweets automatically using this technique? Thanks again, Guy

Shakir
Guest
7 months 15 days ago

Your skills of teaching others a technical issues. Are Awesome. I really like this one.
Is there any other tutorial for getting Tweets Dynamic.
Means
As i tweet It makes a change sudden on my page. Looking forward for tutorial from your side based on my query.

Arsalan
Guest
Arsalan
7 months 16 days ago

HI
first of all thank you for explaining in so much detail.
I wanted to know how can I extend the code to get tweets in real time, for example tweets automatically get updated as new tweets come in.
Thank You

Jomar Rodenas
Guest
Jomar Rodenas
7 months 25 days ago

Hi, I am currently studying this code for a project. But, I’m having a hard time understanding this PHP script. Is there a way I can put all the gathered data in a MySQL database? If yes, where should I put it. I would gladly appreciate if someone would reply or help me with my problem.

Radu
Guest
Radu
7 months 27 days ago

Hi Ian,

For some odd reasons I am getting a PHP error ” Invalid argument supplied for foreach()”. I have noticed that several other people faced this and tried what you suggested but nothing worked…

I am running on Xampp 3.2.1. And i Have checked the result. It looks like a JSON object… so I asume that response in “” foreach($response as $items) “” is not array! Any suggestions?

Brecht S
Guest
Brecht S
7 months 28 days ago

Your code works perfect for me but in the text i got the url. How can i get the url as a $items[‘url’] or something like that?

Donatus
Guest
8 months 5 hours ago

Hi Ian,
This is great work, I tested mine and it works fine. But have one question… How can I be able to get notifications send from other users to my account? For example if my account name is @donatuss, when people SMS to my account thy use “@donatus Message-content”….. how can I be able to get these? Thanks for your help…

VK
Guest
8 months 24 days ago

Can someone explain how to make REST API Calls without the getfield string. To be more clear “https://api.twitter.com/1.1/trends/available.json” is the resource url that does not support any parameters. According to the tutorial we add the parameters in the “getfield” string.

$getfield = ""; // Should this string be empty ?? Is this necessary ??
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield) // Is this setGetField method call required ??
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
 

Also will be grateful if somebody could help explaining how I could have “the locations that Twitter has trending topic information for”. [URL – https://api.twitter.com/1.1/trends/available.json%5D

Avinesh
Guest
8 months 27 days ago

Awesome tutorial to start with but I am stuck at one place. Let me post my error so that somebody can come to the rescue.

Fatal error: Uncaught exception ‘Exception’ with message ‘couldn’t connect to host’ in /home/a2302141/public_html/iTest/TwitterAPIExchange.php:280 Stack trace: #0 /home/a2302141/public_html/iTest/iTest.php(16): TwitterAPIExchange->performRequest() #1 {main} thrown in /home/a2302141/public_html/iTest/TwitterAPIExchange.php on line 280

Avinesh
Guest
8 months 27 days ago

Some extra details:

1) Tried the solution discussed already (the one that recommends changing the SSL_VERIFYPEER) but the error persists.
2) Currently using the free hosting hosting site (000webhosting)
3) Site url – http://itweets.netau.net/iTest/iTest.php

Thanks in Advance !!

Tyler
Guest
Tyler
8 months 26 days ago

Hey Avinesh,

I was having the same error with 000webhost (see my post below yours). I read somewhere that 000webhost is blocked from twitter because so many people have been using it to pull data. (Doesn’t make much sense to me either). I am currently figuring out a good place to host the script. If you come across any other site (a lot of them are the same like 000webhost, byethost, etc) make sure to post it back here to help others with similar problems.

Avinesh
Guest
8 months 25 days ago

Tyler FYI,

Issue resolved !! Do not trust any free hosting sites for they will make you folly. I happened to host my code on GoDaddy (Not a free trial) and all worked perfect like a magic. Thanks again to Ian for his wonderful explanation ..

Tyler
Guest
Tyler
9 months 1 hour ago

I have done all the steps, and I am currently running the php script locally on my computer.
I want to have it just print the tweet itself, and who tweeted it. For example:
"This is a tweet"
"@FromThisUser"

However, I am coming across a few errors. Right now my code that runs the “GET” looks like:

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user']))  {$user = $_GET['user'];}  else {$user  = "tylerjameshuey";}
if (isset($_GET['count'])) {$count = $_GET['count'];} else {$count = 1;}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
              ->buildOauth($url, $requestMethod)
             ->performRequest(),$assoc = TRUE);

?>

but when it runs, it comes out as gobbilty gook.

(For example):

 [{"created_at":"Mon Sep 28 15:47:15 +0000 2015","id":648524380536983552,"id_str":"648524380536983552","text":"Test Tweet","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":430330109,"id_str":"430330109","name":"Tyler Huey","screen_name":"tylerjameshuey","location":"","description":"#RU16","url":"http:\/\/t.co\/yKAzxoIUiz","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/yKAzxoIUiz","expanded_url":"http:\/\/www.facebook.com\/tylerjameshuey","display_url":"facebook.com\/tylerjameshuey","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":69,"friends_count":78,"listed_count":3,"created_at":"Wed Dec 07 01:32:57 +0000 2011","favourites_count":71,"utc_offset":-10800,"time_zone":"Atlantic Time (Canada)","geo_enabled":false,"verified":false,"statuses_count":609,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/3045999885\/10a141f7ef48009462dfa572e8bb2e63_normal.jpeg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/3045999885\/10a141f7ef48009462dfa572e8bb2e63_normal.jpeg","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"has_extended_profile":false,"default_profile":true,"default_profile_image":false,"following":false,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"symbols":[],"user_mentions":[],"urls":[]},"favorited":false,"retweeted":false,"lang":"fr"}]

Also, when I include foreach($string as $items) I get an error that shows up after all that gook that says : “Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\testing.php on line 24

Can you help out at all?

Julie
Guest
9 months 1 day ago

This is a brand new endeavor for me. I seem to be doing something wrong. I kept it simple – following your initial steps for setting up an app in Twitter and getting the keys and tokens. I uploaded the latest TwitterAPIExchange.php from the link you had. I copied and pasted the app content from above and changed the access tokens and consumer keys. That’s pretty much all I did. When I run the program I get an error message as follows: “Could not authenticate you.”

What do I need to do to be authenticated other than including the access tokens and consumer keys?

sinbu
Guest
sinbu
9 months 12 days ago

what if i want to collect tweets for all trending topics or all the tweets filtered through a keyword ?

vis
Guest
vis
9 months 14 days ago

can i use this library to stream data ?

humza
Guest
humza
9 months 15 days ago

great..!!!
i want to get all the tweets for a trending topic or all the tweets that contain a particular keyword. Also, the tweets should be from all the users (not a particular user).
what shoud i do in that case.
Thanks in advance. A quick reply is appreciated.

Max Galka
Guest
9 months 19 days ago

Thanks. Very helpful tutorial!

Kevin
Guest
Kevin
9 months 21 days ago

Thank you for a great tutorial Ian!
Everything is completely understandable but I still can’t get it to work…

I get the same error as “Reed” –

Fatal error: Uncaught exception 'Exception' with message 'couldn't connect to host' in /home/u644281071/public_html/test/TwitterAPIExchange.php:305 Stack trace: #0 /home/u644281071/public_html/test/stepbystep.php(22): TwitterAPIExchange->performRequest() #1 {main} thrown in /home/u644281071/public_html/test/TwitterAPIExchange.php on line 305

I tried the same php file with another host to see if it had someting with an unsupported cURL to do, but I got the same error. What am I missing here?

Stephen
Guest
9 months 29 days ago

Great tutorial, i can’t believe I got it working. That is up until the loop. I was receiving the json info with the print function but when I applied the loops all i get is the echo text, no info from the actual tweets. Help, please

Time and Date of Tweet:
Tweet:
Tweeted by:
Screen name:
Followers:
Friends:
Listed:

Stephen
Guest
9 months 29 days ago

I see where I went wrong. Your code works great. I was trying to search and haven’t formed the query properly. I eventually want to have the search term a variable from a get but thats another tutorial I am sure. Here is what I had.

$url = “https://api.twitter.com/1.1/search/tweets.json”;
$requestMethod = “GET”;
$getfield = ‘?q=forgive%20me&count=1’;

Akhilesh Shukla
Guest
10 months 1 day ago

Thank you so much for writing this great tutorials. It works for me.

Reed
Guest
Reed
10 months 14 days ago

Hey! I love the tutorial so far but I’m getting an error.

Fatal error: Uncaught exception 'Exception' with message 'couldn't connect to host' in /srv/disk10/1930922/www/qualifiedllama.co.nf/TwitterAPIExchange.php:305 Stack trace: #0 /srv/disk10/1930922/www/qualifiedllama.co.nf/index.php(27): TwitterAPIExchange->performRequest() #1 {main} thrown in /srv/disk10/1930922/www/qualifiedllama.co.nf/TwitterAPIExchange.php on line 305

Went to line 305 and the curl_close is there which some people on stack overflow suggested I check. know any way to fix this? I can provide any additional information that you may need.

handy
Guest
handy
10 months 25 days ago

Hi Ian, I need feed all tweets and i have found a to discuss of you with fiona. I code with your guider but i only get about 3200 post. I want to get all. (sorry maybe My English is bad. )

This is my code:

 "",
    'oauth_access_token_secret' => "",
    'consumer_key' => "",
    'consumer_secret' => ""
);

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$twitter = new TwitterAPIExchange($settings);


$getfield = "?screen_name=nytimes&count=20&trim_user=true&max_id=627046084376924160";
$response = $twitter->setGetfield($getfield)
			 ->buildOauth($url, "GET")
			 ->performRequest();
$json = json_decode($response);
echo "";
//print_r($json);
getdata(NULL);

function getdata($max_id)
{
	$number=0;
	global $twitter;
	global $twitter_acc;
	global $count;
	global $url;
	$getfield = "?screen_name=$twitter_acc&count=$count&trim_user=true".($max_id? "&max_id=$max_id": "");
	
	try{
		$response = $twitter->setGetfield($getfield)
					 ->buildOauth($url, "GET")
					 ->performRequest();
	}
	catch(Exception $e)
	{
		echo "Loi: ".$e->getMessage();
		sleep(3);
		return getdata($max_id);
	}
	
	$json = json_decode($response);
	
	if(sizeof($json) != 0)
	{
		$m = new MongoClient();
		$db = $m->Feed_Twitter;
		$collection = $db->feed_tw_ex;
		
		foreach($json as $item)
		{
			
			$item->created_at = new MongoDate(strtotime($item->created_at));
			$collection->insert($item);
			echo ++$number.PHP_EOL;
			echo 'Save '.$count.' Post '.PHP_EOL;
			
			$max_id = $item->id;
		}
		
		getdata($max_id - 1);
	}
	else
		return;
}
echo "ok";
handy
Guest
handy
10 months 25 days ago
    'oauth_access_token_secret' => "----",
    'consumer_key' =>; "----",
    'consumer_secret' =>; "----"
);

$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$twitter = new TwitterAPIExchange($settings);


$getfield = "?screen_name=nytimes&count=20&trim_user=true&max_id=627046084376924160";
$response = $twitter->setGetfield($getfield)
			 ->buildOauth($url, "GET")
			 ->performRequest();
$json = json_decode($response);
echo "";
//print_r($json);
getdata(NULL);

function getdata($max_id)
{
	$number=0;
	global $twitter;
	global $twitter_acc;
	global $count;
	global $url;
	$getfield = "?screen_name=$twitter_acc&count=$count&trim_user=true".($max_id? "&max_id=$max_id": "");
	
	try{
		$response = $twitter->setGetfield($getfield)
					 ->buildOauth($url, "GET")
					 ->performRequest();
	}
	catch(Exception $e)
	{
		echo "Loi: ".$e->getMessage();
		sleep(3);
		return getdata($max_id);
	}
	
	$json = json_decode($response);
	
	if(sizeof($json) != 0)
	{
		$m = new MongoClient();
		$db = $m->Feed_Twitter;
		$collection = $db->feed_tw_ex;
		
		foreach($json as $item)
		{
			
			$item->created_at = new MongoDate(strtotime($item->created_at));
			$collection->insert($item);
			echo ++$number.PHP_EOL;
			echo 'Save '.$count.' Post '.PHP_EOL;
			
			$max_id = $item->id;
		}
		
		getdata($max_id - 1);
	}
	else
		return;
}
echo "ok";
trackback

[…] twitter accounts. I want to get his total followers and post tweets to his accounts. This is the article I kept for […]

Sajeev C
Guest
Sajeev C
11 months 13 days ago

This is definitely one of the best tutorials available over internet. You are a great teacher. And James Mallison has also done a great job by providing an easy to use wrapper script.
How can I add signin/signup facility with the wrapper class? I know this question should be pointed towards James, but even then, have you done something like that with the script?

Thanks. Gracias. Great Day.

isubmitsite
Member
11 months 13 days ago

I wonder if anyone could recommend a page with sample code for authorizing an app to other users. Basically the same thing that I did here when I allowed access to my twitter so I could post this message.
I have code that I use for tweeting and following etc. but I cant seem to find any information that will help me understand the flow of that process where my app will be authorized to use other accounts. twitter dev section does little to help me. It does give a url to use. but then what is next. well, anyway. if anyone could recommend a good link with some php example code that would be really helpful.

Amm Dhillon
Guest
11 months 15 days ago

Hey, It’s a great article but I’m having trouble finding where am I wrong. I am not a programmer but I guess I did everything as you mentioned.
help please

Parse error: syntax error, unexpected ” (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /home/genuisno/public_html on line 15

staarbyte
Guest
staarbyte
11 months 18 days ago

To start off, thanks a ton for this amazing article! I’m super new to PHP and APIs but this was incredibly easy to follow and I feel like I learned a lot 🙂

It works pretty good for me, but there’s just one thing – the tweets display fine at the bottom of the page when I open the file (my chosen url is the user_timeline), but the cache is still showing up on the page and I’m not sure why. I think I’m making a newbie mistake haha. Can you tell me which part of the code is responsible for erasing that part and only displaying the content of the foreach loop, like your example?

I don’t know if it has anything to do with it, but I’m also getting this line here at the bottom of the cache:
“Notice: Undefined index: errors in [my link directory] on line 30”
and line 30 is the if statement that catches errors. The line itself disappears if I comment it out, but the cache still stays.

staarbyte
Guest
staarbyte
11 months 18 days ago

I was indeed making a newbie mistake. I accidentally left in the “echo” statement in front of the request statement, whoops!

KeenNaqvi
Member
11 months 21 days ago

Its not working for me.. Don’t know where am I going wrong.. I’m new to such APIs..
Its generating the following error:

Fatal error: Uncaught exception 'Exception' with message 'SSL certificate problem: unable to get local issuer certificate' in C:\xampp\htdocs\twitteroauth\application\controllers\TwitterAPIExchange.php:297 Stack trace: #0 C:\xampp\htdocs\twitteroauth\application\controllers\twitter_2.php(17): TwitterAPIExchange->performRequest() #1 C:\xampp\htdocs\twitteroauth\system\core\CodeIgniter.php(251): include('C:\\xampp\\htdocs...') #2 C:\xampp\htdocs\twitteroauth\index.php(202): require_once('C:\\xampp\\htdocs...') #3 {main} thrown in C:\xampp\htdocs\twitteroauth\application\controllers\TwitterAPIExchange.php on line 297

julia
Guest
11 months 26 days ago

I was create this application but, I can’t adding automatic favourites and adding friend before mention it,..

may you can help me,.my application now only mention every account which match search keyword

I need script for auto follow and auto favourites after match with my keyword search

Thanks So Much Before

WeerSan
Guest
11 months 27 days ago

Very helpful edition to my project. Thank you sir!

Calum
Guest
Calum
11 months 30 days ago

Nevermind I’ve got it!

wpDiscuz