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 Editor 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 onto 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 unified 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. Huge 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 and 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 GitHub repository and download it from here.

GitHub
Once you've downloaded 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 an 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 to us. In this case, we want to receive the last 20 tweets from the 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, let's 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. Thanks to Jay (in the comments) for an update on this line:
if(array_key_exists("errors", $string)) {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(array_key_exists("errors", $string)) {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 around 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 around 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. And, because there are some nasty hackers out there, we'll also want to check and remove any non-alphanumeric characters that they may want to add.
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_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.
Please note: I don't recommend setting these variables using the GET string on a public facing site. It could all to easily be abused by hackers. This will get you up and running quickly, but I recommend either hard-coding the variables, or doing some safety checks on the GET variables before you use them.
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 = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
if (isset($_GET['count']) && is_numeric($_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(array_key_exists("errors", $string)) {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 into the Twitter API world. Have fun!


Excelent! Let me ask you one more question… what should I use to search keywords in tweets? I understand that $items[‘full_text’] is used to print in screen the full text, of the tweets of the timeline… I want to know what should I put in $url and $getField to search for any word in tweets from any user…
Thanks a lot!!!!
Hello sir,
how can i get full details of tweets with images. using your code i am getting [‘text’] variable but it not contain full description of tweets
Hi Ritesh,
Great question! Since Twitter expanded from 140 to 280 characters, you now need to use
$items['full_text']instead.['text']only gives you the first 140 chars. Does that help?Excelent! Let me ask you one more question… what should I use to search keywords in tweets? I understand that $items[‘full_text’] is used to print in screen the full text, of the tweets of the timeline… I want to know what should I put in $url and $getField to search for any word in tweets from any user…
Thanks a lot!!!!
This is fantastic. I didn’t know it would be as easy, or relatively easy to do. I’m good a php but I see some things in the code which I need to brush up on, for example the -> notation. Anyway, thanks for this.
Hi Shane, Glad you found this useful. That was definitely my intention. I got so fed up with tutorials that were difficult to understand. Ian
Hi Ian,
Can I Go live to twitter programmatically using .Net
Hi Maddy, yes I’m sure this will be possible. You’ll just need to find a Twitter wrapper built in .net. Sorry, but this is out of my area of expertise. Ian
So far the tutorial is awesome……but I’m getting an error for: invalid foreach arguments that exist on line 23 on the MyLittleApp.php file……Please help me out.
Hi Souchito, I’m not sure what the issue is for you. But I’d check that you have the correct details for Twitter and that Twitter is actually giving you results. If not, then the arguments won’t be valid – because it’s not an array that the foreach can loop through.
Hi Ian,
I’m using abraham/twitteroauth do you hapopen to know how can I post tweets in a other user timeline? I’ve created an app and I accept it in another account for testing that I have, I took a look to the API but with no luck. I don’t know how to get the proper access token and access token secret of my test account for creating a tweet.
Thanks in advance.
Alberto
Hi Alberto, Sorry, I am not familiar with that Twitter OAuth script. But, to get the access tokens for the account you want to post as you need to be logged in to that account and then follow the instructions here – https://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/
Thanks This is great!
Question. How would i get this to refer to my .ENV file to get my twitter credentials? i am using laravel and installed with composer. I see the package in Vender but all the $settings fields are “”. I wish they would just point to .ENV. how would i do that?
Hi Ben. Really sorry, but I’ve not used Lavarel or composer. I know I should, but just never invested the time. Ian
thanks very nice
When testing the code from the comand prompt it works great (although a wee bit slow – taking about half a second to execute). However, when running it from the browser, nothing happens. No errors. Just… nothing. Execution of the script ends, so no code “behind” the twitter call is executed. Am I missing to set some headers or something? I am running the latest versions of PHP and all. The fact that it WORKS when running it from the commend prompt ($ php twitter.php) but not when surfing in to http://example.com/twitter.php (commend prompt and urls etc are simplified for example only) has me a bit perplexed. Yes, all files are in place, no paths are off etc – the entire HTML page is returned when running from the prompt.
Hi Per. That’s odd. So, no errors at all? Are you not getting an error from Twitter itself? Is the request being received by Twitter? It’s very difficult to know without more digging. Let me know how you get on. Ian
Bravo!
this has stopped working December 2017
Hi Luke. Could you give me more information? It’s still working for me. Are you getting an error message? Let me know and I’ll look into it. Ian
Hi, I have a problem. I want to get all my followers information but I’m recieving this error “Too Many Requests”. Is there a way to do this? I haven’t found information about it and I’m desperate. Thanks.
Hi Oscar,
Unfortunately, Twitter has strict limits as to how many requests you can make every 15 minute period. You’ll just have to reduce the number of requests and run it again once the 15 minutes are up. Ian
Great!
Thanks Ian really good explained and easy to follow.
i made it hhahha
That’s great to hear. Glad I could help. Thanks for letting me know.
could not get it to work for POST
Sorry you couldn’t get it to work. I’ve not covered how to use POST in this article. But there is a really helpful article on the GitHib repo for the script here: https://github.com/J7mbo/twitter-api-php
How about to get public tweets from a specific location ? Can you help me ?
is it possible to get ALL live tweets containing specific keyword?
Hi, yes, you can do this by using the search part of the Twitter API. Check here – https://dev.twitter.com/rest/reference/get/search/tweets You’ll want to set return_type to recent too. Bear in mind that this doesn’t give you all results – it’s focussed on relevance.
i want for dynamic timeline , like for any user login then his/her timeline should be displayed , its showing static timeline …
TwitterAPIExchange.php file is required.
so file is not here.
?????
Hi, No doubt, You have done a super description, But it’s not working for me. I have exactly copied your script with changes on tokens, and secret keys.
I have also specified my domain and folder path on twitter app settings. But this is not just giving me any kind of output. Please Help me
Hi there are you getting any type of errors and where are you going to use this code (website,game or app)
Super description, thank you. I’m looking for a way to add a message to a twiiter with a photo. I have a news page and a rss feed (http://imoje.pl/rss.php). News to be added from the rss feed. How to use POST to have a message, a picture and a link to the message. Thank you for your help.
Hi, How to get the first tweet with any new hashtag using PHP.
Is this the first Tweet in a search for a specific hashtag? If so, you’ll need to do a search request. Is it your tweet that contains that hashtag?
Well, you could use search (using the advanced search function to search for the hashtag from you) or you could return your tweets and then go through your latest tweets in the loop checking for the hashtag in the Tweet text.
Hi There I’ve tried this code on localhost Mac and works like a charm but when I load it to a windows pc I get an error “invalid argument supplied for foreach()” any ideas
Hi there. I am sure this has something to do with security certificates, but unfortunately, this is outside of my area of knowledge. I personally prefer to use a web host for this because it should just work. Doing it locally requires setting the environment properly so that cURL works.
Superb, it took me days to get the Facebook API working. Just followed this post and I’m connected and working with the API in less than an hour!
Thank You!
Thanks, Ben. Your comment made my day! I need to do a similar post on the Facebook API, but first I need to understand it – and their docs really don’t make it easy!
Reading and reading… and puzzling on https://dev.twitter.com/rest/reference/get/search/tweets
But cannot get it work properly unfortunately.
Your above script with active links (information from the discussion) works perfect.
But a working Get Search Tweets seems more difficult.
Thank you!
Hi Piet, Yes, the search request is a little different. For some reason, Twitter puts the data in the
statusesarray.So, to make things easier, you could add the following line just before the
foreachline:That way, the
foreachline will loop round the data within the statuses. A bit difficult to explain, but I hope that makes some sense!It works perfectly, thank you again Ian!!
So glad it worked for yuo, Piet! Ian
THANK. YOU!
You clarified the most confusing thing EVER in 10 minutes.
YOU ARE THE MAN. Please keep it up.
Thanks, Nick, you made my day. That was TOTALLY my aim in writing this article. I hate when developers make things difficult to understand.
Hi Ian,
thanks for sharing this awesome tutorial! I’ve seen some tutorials the past week, because I’m trying to get started in PHP, but a lot of them miss some aspects.
Getting started in PHP and an API seems a little bit overwhelming, but the motivation is bigger – because you get a quick result (if it works ;))
Please keep up the good work,
Sebastian
(P.S.: One image link in the post seems to be broken.)
Thanks, Sebastian. That’s awesome. All the best with getting to grips with PHP and APIs. It is very overwhelming, so you’re not alone in that. Glad this article helped.
Thanks also for the heads up on the broken image. I am sure I fixed that before, but it keeps on coming back!
Ian
blank page arrive ??? any solution i m working in localhost
As I mention in the article, this works best in a web hosting environment. If you want to use localhost, you’ll need to configure the certificates correctly which isn’t something I know much about. However, others in the comments have made it work. Have a look and hopefully you can get sorted. Ian
Hey Ian Anderson, I wanna retrieve particular or recent and trending Hashtags tweets use by the people automatically and want them to save automatically to my application, how can I do this.. need help thanks
Hi Ashna. You’ll need to modify the example above and use the trends/place request. For more information see here – https://dev.twitter.com/rest/reference/get/trends/place
blank page arrive ??? any solution
Fatal error: Class ‘PHPUnit_Framework_TestCase’ not found in C:xampphtdocstwitterTwitterAPIExchange.php on line 11
Dude…I know its too late to reply but for others facing same error I think u have copied wrong file from given github path . The file you need to copy existing below test folder not inside the test folder. please correct me if i am wrong.
Nice tutorial
But you should absolutely NOT use raw GET parameters in your $getfield variable! There will be many people who copy/paste this code and leave themselves open for injection attacks.
Very true! It’s not to be recommended on a public site. I just wanted to give a quick demonstration. However, I probably should add a little note with a warning! Thanks for the heads up!
Ian
bro u can understand i m student i want make project , can you help which changes require , come blank page in localhost?????
Hi there. As I mention in the article, the tutorial assumes you are using a webhost – not localhost. I’ve not tested it on localhost. The issue you are having is likely to do with SSL certificates not being installed properly.
If you heck the other comments here you’ll hopefully see some workarounds from people who have got it working. Sorry I can’t help any further, but it isn’t something that I have tried.
Could you suggest what alternative there is to a raw $getfield variable which would reduce this risk?
Hi Chris, that bit is completely optional. But you did remind me to update the article with a better option, and so I have. See the update above!
This was awesome, quick and easy. I got it up and running in under 15 mins.
So glad to hear, that was my intention!
Ian
Hi. Thank you …Ian
My pleasure!
Best Twitter app code ever!
Thanks! So glad you found it helpful! Ian
Thank you my Friend! It worked perfectly! Now i just have to figure out, how to GET how often a certain URL has been tweeted. (Maybe someone has an Idea how?)
P.S.: Struggled the whole day with the filthy Fa***ook-API, and this worked in Minutes, wtf.
My pleasure. I feel your pain with the Facebook API. Everyone goes on about who easy it is supposed to be. My aim in this article is to actually make an API easy. I need to get my head round the Facebook API next! I’ll be honest, I am not sure how you’ll do what you want to do. Perhaps you could use the Twitter Search request and search for the url. It probably won’t be very accurate, but you can see the Tweets that contain that URL.
Hi. Thank you for your great tutorial.i have question.i want to search spacial tag .i changed the url:$url = “https://api.twitter.com/1.1/search/tweets.json”; and $getfield = “?q=hello&count=20”; and i can print it with print_r but i dont know how to print it with foreach loop.please help me.
Uncaught exception ‘Exception’ with message ‘error setting certificate verify locations: CAfile: ”C:\xampp\php\extras\ssl\cacert.pem” CApath: none’ in C:\xampp\htdocs\TwitterAPIExchange.php:317 Stack trace: #0 C:\xampp\htdocs\littleapp.php(21): TwitterAPIExchange->performRequest() #1 {main} thrown in C:\xampp\htdocs\TwitterAPIExchange.php on line 317
I am getting this error everytime ..Can this be solved
It sounds like you don’t have certs set up properly on your local set up. I’ve not tried this in a local environment, but a few other commenters have had some success. Have a look through and see if they help.
Hi, I used the code above but got an invalid argument pertaining to my file location.
this is it
! ) Warning: Invalid argument supplied for foreach() in C:\wamp64\www\php\forumTest.php on line 71
Call Stack
# Time Memory Function Location
1 0.0038 251952 {main}( ) …\forumTest.php:0
for the life of me i can not figure it out?
by the way it shows up on the website where the user timeline should be
Hi Tian. It is difficult to know exactly what the issue is without seeing the code. What is on line 71?
Hi it is showing {“errors”:[{“code”:32,”message”:”Could not authenticate you.”}]} this error please help
Hi Kiran. Check you’ve got the correct Twitter token information. Twitter can’t authenticate you with the information you’ve provided. Ian
do we have to write the tokens and the consumer key in double qoutes in the $setting array?
Hi Satvik, yes, that’s exactly it! Ian
how can i get the tweets that contains a specific hashtag?
Hi Satvik,
It depends on what you’re wanting to do. Are you wanting to do a Twitter search for a particular hashtag, or filter your results by a hashtag?
hi sir.
Fantastic tutorial. God Bless You. Thank you thank you thank you. You save me.
Thanks so much. You’ve made my day!
Ian
Hi All,
Looks like a great PHP wrapper.
Having an issue making it work.
sportsday:~ # php -f index.php PHP Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /root/TwitterAPIExchange.php on line 315 Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /root/TwitterAPIExchange.php on line 315 PHP Fatal error: Uncaught exception 'Exception' with message 'error:0D0C50A1:asn1 encoding routines:ASN1_item_verify:unknown message digest algorithm' in /root/TwitterAPIExchange.php:315 Stack trace: #0 /root/index.php(38): TwitterAPIExchange->performRequest() #1 {main} thrown in /root/TwitterAPIExchange.php on line 315 Fatal error: Uncaught exception 'Exception' with message 'error:0D0C50A1:asn1 encoding routines:ASN1_item_verify:unknown message digest algorithm' in /root/TwitterAPIExchange.php:315 Stack trace: #0 /root/index.php(38): TwitterAPIExchange->performRequest() #1 {main} thrown in /root/TwitterAPIExchange.php on line 315 sportsday:~ #Could this be an issue with openssl or Curl?
Thanks for your help.
Andy
Hi Andy. Talk about unhelpful error messages! I am really not sure what the issue is here. Are you running this locally or on a web host?
Hi Ian,
Looks like we found the issue, the PHP OpenSSL module was not working correctly, we removed and reinstalled and it’s working fine now,
Do you have an example of submitting a “Tweet” using your Wrapper?
Thanks for your help
Andy
Hi, Andy. That’s great to hear you found the problem and were able to fix it. You can send a Tweet using the wrapper, but I haven’t written about that. I hope I can get the time to write a follow-up article, but I have been saying that for a while! I recommend reading this response by the wrapper’s author as he goes into all the detail you’ll need about this. Let me know if you have any more questions. Ian
Hi ian
what is the different between id and id_str?
I think they are pretty much the same. However the id is presented as a number in id and as a string in id_str.
how to display the post items along with image
Sorry, I don’t quite follow you. What post items are you referring to?
Great tutorial. One problem I’m running into is when I try to get the users website/url(mentionedintwitterprofilenotintweet.)
I’m using
echo “Website: “. $items[‘user’][‘url’].””;
It returns with a t.co link(which redirects to the users website) but I want it to return the actual link(the expanded url of the users website mentioned in profile.) Any way to do this?
Thanks!
I know the Twitter API docs are pretty unhelpful, but do have a look at the code – it can show you which bits of data are available.
I’ve not tested this but you need to get the
expanded_urlfrom the bio url. So this should work$items['user']['url']['urls']['expanded_url']Ian, many thanks for this excellent article. I just one question. I’m trying to count the favorites for a specific tweet. Is there any way to do this?
Sorry for the delay. I’ve not tried this, but there is a
favorite_countentity you could try.echo "Number of likes: ". $items['favorite_count']."<br />";Is there a way i can make the links active, I mean make the # tags and the direct mentions clickable, I would really appreciate it.
I mentioned this in a comment below – but there have been quite a few comments and it got lost!
You could add the following code from this pastebin: http://pastebin.com/gJs9nb7e
Then on line 23 in the example script in the article use the twitterize() function to convert the tweet text to the one with links:
echo "Tweet: ". twitterize($items['text']);Brilliant thanks for making it easy to understand! I found out that there are 2 api’s the normal one and a streaming one. what would I need to get the streaming api to work to get a continues feed? your help would be appreciated.
Hi Ross. This article is all about using the normal API – not the streaming one. To be honest I haven’t had the chance to look at the streaming API yet. The wrapper script I use in this article won’t work with the streaming one unfortunately. I’d see if there is a tutorial on the streaming API out there or search Github to see if there are any PHP wrapper scripts for it. Sorry I can’t help with this one.
Hi Ian Anderson Gray,
Your tutorials are great and very easy to understand, this one is the best, I am a new Php app developer and your tutorial helps me a lot to making things really easy.. I have just an issue while running it,
it shows
[Fatal error: in C:\xampp\htdocs\twitter\TwitterAPIExchange.php on line 315] if (($error = curl_error($feed)) !== '') { curl_close($feed); throw new \Exception($error); } curl_close($feed); return $json; Line 315: throw new \Exception($error);please tell me what the problem is, and how it can be solved
Hi Ashna, thanks for your kind comment!
I am not exactly sure what the problem is. Are you developing locally? I’ve not tried developing on a Windows based server, but it should still work.
If you are developing locally, the issue could be to do with cURL and no certificates being installed.
As I mentioned below, try the following…
Change
CURLOPT_SSL_VERIFYPEERfromtruetofalsein the TwitterAPIExchange.php file.Thanks It solves this problem, and thanks a lot for your co-ordination
, really you are the best tutorial maker and author (y)
Hi Sir,
I wanna displaying tweets that contain a certain hashtag, as data set. do u have any tutorial about this subject or any suggestion for me?
Hi, sorry I missed your comment. I don’t have any tutorials on that at the moment. You’ll probably want to use the search feature of the API – https://dev.twitter.com/rest/reference/get/search/tweets
Then you can return Tweets that contain your hashtag. I hope to expand this tutorial at some point, but I haven’t had the chance yet.
tanx alot.
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
You’re having certificate issues because they haven’t been set up properly in cURL. This isn’t usually an issue if you are using a good host, but it looks like you’re running this locally.
As I mentioned in an earlier comment…
Change
CURLOPT_SSL_VERIFYPEERfromtruetofalsein the TwitterAPIExchange.php file.i can
t find CURLOPT_SSL_VERIFYPEER in TwitterAPIExchange.phpt find iti am already search it and i still didn
i just include CURLOPT_SSL_VERIFYPEER = true in setting in TwitterAPIExchange.php file and it works.
are we using different version of TwitterAPIExchange?
I am not sure. Perhaps the script has been updated since, but basically adding that line should solve your problem. Thanks for sharing. Ian
You need to add the line CURLOPT_SSL_VERIFYPEER => false,
In order to get it running from a localhost
Thanks!