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 (only the first 140 characters)
- full_text - The text of the tweet (all 280 characters - but only if you use the tweet_mode=extended option in the query)
- 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 />"; }
Update - since Twitter moved from just 140 characters per Tweet to 280, you can't rely on getting the full Tweet from $items['text']
anymore. You'll need to use <code?$items['full_text']. But you only use this if you add tweet_mode=extended to the query string. So we'll add this to our $getstring:
$getfield = '?screen_name=iagdotme&count=20&tweet_mode=extended';
Thanks to Alexander (in the comments) for reminding me about this update!
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&tweet_mode=extended";
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&tweet_mode=extended"; $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['full_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!
Sorry, but due to time constraints, I am not able to offer any support in this comment thread.
However, feel free to ask, and hopefully one of the other commenters will be able to help.
Beautiful tutorial and the only confusion I had was I reversed the key sets; maybe that is something to clarify; however, I am actually here because I wanted to know if anyone has had any success with tweeting to your own account. I want to send tweets based on status changes i have going on with my website and then people will get notified of the change if they are subscribed to my twitter feed…. so far my attempts at tweaking littleApp.php has not worked… IF ANYONE has done this can they post there code?
very usefull.thank you man. that solved my problems
That’s great! So glad this helped!
Where do I get all those keys? twitter dev only gives me API key, API secret key and Bearer token?
What is the purpose of this?
It returns 20 and my tweet is not posting my feed.
It’s if you want to increase the number of results to beyond 20. If you want it more than 20, you can just add ?count=100 (or whichever number you want) to the end of the URL. Hope that helps. Ian
Really nice and easy way to get a twitter feed, than you Ian Gary. I have a blog with a twitter feed, just wanted to know how to convert the @mentions and links in the tweet text to actual anchor elements that go to the relavent URLs. Thanks again.
Sorry, Vishal, I don’t have experience with Laravel, and I can’t offer support on that. Hope you manage to get it sorted.
Thank you so much , you gave me a valuable stuff. this is really worked for me. thank you again, sir.
Fatal error: Uncaught Exception: SSL certificate problem: unable to get local issuer certificate in C:\MAMP\htdocs\TwitterAPIExchange.php:321 Stack trace: #0 C:\MAMP\htdocs\index.php(38): TwitterAPIExchange->performRequest() #1 {main} thrown in C:\MAMP\htdocs\TwitterAPIExchange.php on line 321
I am getting this error, please help
Great app, many thanks – i grabbed your code from here: https://github.com/iagdotme/MyFirstTwitterApp
How do you include images with this?
I am now getting this error:
[email protected] [~/php]# php twitter_image_tweet1.php
Fatal error: Uncaught RuntimeException: TwitterAPIExchange requires cURL extension to be loaded, see: http://curl.haxx.se/docs/install.html in /home/birdsey8/php/TwitterAPIExchange.php:84
Stack trace:
#0 /home/birdsey8/php/twitter_image_tweet1.php(27): TwitterAPIExchange->__construct(Array)
#1 {main}
thrown in /home/birdsey8/php/TwitterAPIExchange.php on line 84
According to my ISP, instead of extensions, cURL is part of the PHP install.
Is there a workaround for this?
Thanks
Robert
Hi Robert, Sorry for the issues you’ve been having. Unfortunately, this is outside of my knowledge. Can your host give you any more help? If The TwitterAPIExchange.php script is saying that cURL isn’t there, then it isn’t there – or it’s not configured in the usual way. I’d ask your host to look into it. All the best! Ian
I am getting this error.
Any ideas why?
PHP Syntax Check: Parse error: syntax error, unexpected ‘;’ in your code on line 13
if (isset($_GET[‘count’]) && is_numeric($_GET[‘count’]) {$count = $_GET[‘count’];} else {$count = 20;}
Thanks
Robert
Hi Robert,
So sorry for not getting back to you. Did you work it out?
You forgot a ‘)’ in your code.
It should be:
Notice the extra “)” after the second $_GET[‘count’]
I have filled the setting from a file like this:
Description: The Keys and Token are in a textfile in this format: ApiKey:XXXXXXXXXXXXXXXXXXX, so I have to split it, to get the second parts.
Well, it works, I have verified the settings Array with my keys, but Twitter throws a Bad Authentification error:
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
But if I write the Keys and Tokens directly into the array, it all works …
I don’t have any clue about that s***, but that is is, what I hate in being a programmer …
Not sure what the issue is. It’s likely to do with the way the configuration file is and the way you’ve exploded it with colons. But glad it does works in the array. It could be adding stray spaces or other weird formatting.
Nice article. is there any option that one can post tweet from his own server/website. Few years ago I have used this type of script. That script was ready to use, only one have to access the developer token and such things from twitter. Anyway your lets try with your guidance.
Thank you for posting this. Really helpful!
Is there a way to get re-tweets to show full text? As it’s set currently, they are truncated. :beg:
Sorry for the late reply. I actually updated the code. You need to add a query
tweet_mode=extended
and retrieve with the variable$items['full_text']
Thanks for sharing this. I’ve been trying to learn a little PHP. Great post for me and people who already use other languages like asp or asp.net and want to explore PHP. This is very helpful. Keep on the great work. I just want to say that there is no need to dive too deep in PHP if you don’t want to. A versatile coder can just pick what they need for a particular scenario.
Hi Ian, is there a way I can limit the tweet returned by date and location?
Hi. You could check the date and location of each Tweet and display only those with a specific date and location from the loop? But really, I’d recommend checking out the Search API so you can do a proper search based
Hi Ian!;
Thanks for this article, I’m working with this code but I don’t understand how I can get the results in order.
Any idea? Thanks!
Hi. That’s a bit more tricky. From what I understand, Twitter doesn’t allow you to change the order. You’ll have to do that using PHP. It’s a bit out of the scope of this article, but you can re-order arrays with a number of PHP functions. Here is a good place to start with – https://www.php.net/manual/en/array.sorting.php and you could do a search for how to resort arrays in PHP. Hope that helps! Ian
Hello. Thank you for this article. I want to get just tweet text. Other JSON data i dont need. How can i set to get just “text, date etc.” not all of them.
Hi Arif. Twitter gives you all the information in the JSON file – you just need to extract what you need from it. So, just output the bits you need.
How would you get this page to show in HTML format?
It’s already in HTML format. But you’ll need to add any more HTML to the code above. For example p and li tags. It does require hand coding. Ian
Let me ask you a question… How to Use Twitter’s Advanced Search? I can’t understand all those process……
You need to change the
$getfield
into$getfield = “?q=MySearch”
. Then you can put the advanced search into the query.Probably the easiest way to get help with advanced search or construct the URL is by visiting the advanced search page itself – https://twitter.com/search-home It gives you all the advanced search operators. But once you’ve done the advanced search yourself, you can actually grab the q= search query from the URL itself. I hope that makes sense. Ian
Great Article!
I am having a bit of trouble though. I am using the https://api.twitter.com/1.1/search/tweets.json and I change the $getfield = “?q=MySearch” but I am getting a bunch of undefined indexes. Any help would be appreciated!
Thanks, Jim. Sorry for the delay in getting back to you. The array from a Twitter search query is slightly different.
Just add the following line after the
$string = json_decode
line: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!!!!
Hi Pablo, so sorry for the extended delay – I missed your comment! For searching, you’ll need the following.
$url = 'https://api.twitter.com/1.1/search/tweets.json';
and$getfield = "&q=what+you+want+to+search+for";
Hello!
Great article however I am having trouble using the search tweets. I get a bunch of undefined indexes when I echo everything out. Any assistance would be appreciated!
I replied above with some help on this. Hope it helps. Ian
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?“$items[‘full_text’]” only works with the “tweet_mode=extended” option (cf. https://github.com/sferik/twitter/issues/880). If you mofify the “littleApp” file in that way, this superb script works absolutely fine. @Ian: Thank you su much for your works. To fetch the own Twitter timeline in less then 10 minutes is just grandiose! 😀
Thanks so much for reminding me about this, Alexander. I updated my Twools app with full_text, but I had forgotten to mention it in my article and the little app. Thanks!
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
statuses
array.So, to make things easier, you could add the following line just before the
foreach
line:That way, the
foreach
line 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