Build Your First Twitter App Using PHP in 8 Easy Steps


Twitter API using PHP


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 tend to use Notepad++ or Dreamweaver. 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. 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.

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 string 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 date (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'])) {$user = $_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!


Comments- Let me know what you think!

  • Ashley Faulkes

    Nice tutorial. I think I need to make my own Twitter app at some point, because there are views I just don’t get on these Social Media Tools!! Will have to find some time in amongst all the other things I am doing.

    • http://iag.me/ Ian Anderson Gray

      Thanks, Ashley. There are some great social media tools out there, but sometimes they don’t quite do what you want- or they are expensive. This is when developing your own tool might be the answer. Let me know how you get on.

      • Mahfud Foed

        its’n work
        Fatal error: Uncaught exception ‘Exception’ with message ‘You need to install cURL, see: http://curl.haxx.se/docs/install.html‘ in D:rootapitwitter-api-php-masterTwitterAPIExchange.php:37 Stack trace: #0 D:rootapitwitter-api-php-masterindex.php(15): TwitterAPIExchange->__construct(Array) #1 {main} thrown in D:rootapitwitter-api-php-masterTwitterAPIExchange.php on line 37

        • http://iag.me/ Ian Anderson Gray

          In order to use the wrapper script you will need the cURL extension for PHP installed. Pretty much all the hosting environments I’ve used have had cURL installed but you may need to ask yours to install it, or if you’re comfortable, For more information see http://stackoverflow.com/questions/3062324/what-is-curl-in-php

  • eikzlfkr

    This apps is not working..
    You have to tweak the codes

    • http://iag.me/ Ian Anderson Gray

      Hi, thanks for your comment. It is working perfectly for me. can you be more specific with the problem you encountered? I’ll try and help if you give me more details. Thanks!

      • eikzlfkr

        Hello Ian,
        I’m using php 5.4.7, but all I get is blank space. Actually, I’m juat testing your code. May be tomorrow, I will look up to the code. I’ll let you know my progress. Thanks Ian.
        Sent from my BlackBerry® smartphone from Sinyal Bagus XL, Nyambung Teruuusss…!

        • http://iag.me/ Ian Anderson Gray

          That sounds odd. Have you got error reporting switched on? I’ve only tested in PHP 5.2.x, but I can’t think of anything that would mean it wouldn’t work in PHP 5.4.x.

          • Aman Singh

            SIr , I Need Help In CHange Twitter Profile Picture Via API

            HElp ME …

          • http://iag.me/ Ian Anderson Gray

            Hi Aman. The example I gave in this article is a simple one to get you started. It uses the GET request which only GETS information from Twitter- it doesn’t set or change anything. For that you will need to use the POST method. You can have a look at the documentation for the PHP Twitter app on GitHub:
            https://github.com/J7mbo/twitter-api-php

            The API request you will need to use is this one:
            https://dev.twitter.com/docs/api/1.1/post/account/update_profile_image

            However, what is it you are trying to do? Is this an app you are trying to build or are you trying to update your own Twitter pic? If it’s just for you, check out IFTTT. You can update your profile pic based on other actions (for example you could email your profile pic to IFTTT or get it to change if you upload an Instagram pic for example). More info here- https://ifttt.com/channels/twitter/actions/50

          • Aman Singh

            I m Just Stuck With My Software ..

            It does All But Cant Change Twitter Profile PIc

            see here http://www.besoeasy.com/store

          • Aman Singh

            can u just send a php code That Can Update Profile Pic To Whatever But No Eggs .. ?

            I will Thanks u 1000 TIMES FOR THIS

          • http://iag.me/ Ian Anderson Gray

            Hi Aman, sorry for taking a while to get back to you. Unfortunately I can’t provide PHP code for you- at least not quickly. The Twitter API needs to be served the image in the request- i.e. it needs to be posted. This means you can’t just provide a link to the image. I’ll have a think since I would like to write a follow up to this article.

          • eikzlfkr

            Thank You, Ian..
            I just knew that i just can not test this application on my localhost. When i tested on my domain, it works like charm.
            Thank you, Ian

          • http://iag.me/ Ian Anderson Gray

            Brilliant! Thanks for letting me know this works for you.

  • Ammar Alsharekh

    it doesn’t work

    Warning: Invalid argument supplied for foreach() in C:wampwwwtwitterindex.php on line

    I tried print $string

    result is ”

    • http://iag.me/ Ian Anderson Gray

      Hi Ammar. I assume you are using the standalone version of Twools? Unfortunately there were a few bugs in v0.10 of the standalone version which I assume you are using. I’m finishing off this at the moment and hope to roll it out later today.

      The comments system don’t format code very well, so please use something like pastebin and link to it. The best thing to do is to email me (or use the contact form) or join the Twools Community on Google+ – https://plus.google.com/communities/110217878433862480157

      • ozzy hood

        having the same problem as ammmar ..using wamp server

    • adam

      i got mine working on an older php installation after enabling curl. im not using twools…. just creating pages on my box and running with php, apache….
      I couldnt get twools going on the installation where i couldnt get the example going either.
      Also I changed ?username to ?screen_name so i could view other peoples posts. Adam NZ

      • http://iag.me/ Ian Anderson Gray

        Hey guys, if you are using the standalone version of Twools- make sure you use the latest version (currently v0.11.1). Also I think you might need Curl installed as Adam says.

  • jack

    All i get is a blank page, nothing is being returned. i put an echo at the end of the performRequest function, and that comes up so i know its running the code, but i get no twitter information

    • http://iag.me/ Ian Anderson Gray

      That’s strange. Perhaps Twitter is returning an error. Can you output the array of the result by putting print_r($string); at the end of the script (before the final ?>) ? `

      • Salman

        I have this exact problem

        • Salman

          Trying to do it on local host, I read some of the comments below and it seems like it should work on localhost. I put echo at the end of the code make sure it goes through the whole thing, and that comes up so I don’t know what’s wrong. I am using your exact code to test, same settings from tutorial before this.

          • http://iag.me/ Ian Anderson Gray

            Sorry you’ve had problems with the script. I’ve not tried it on localhost. Some people have had success, but it appears some couldn’t get it to work. Ideally you should try it on a web host. That being said, it’s important to try and find out what the issue is. It sounds like Twitter is returning an error and if so, we need to find out what it is. Could you add the following after line 18, just before foreach($string...:
            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();}
            This line will output the error from Twitter (if there is one) and stop the script. We can then see what the issue is. Could you try that and let me know? You can either do this, or fill in the contact form (see the link above).

          • Mahfud Foed

            I have paste the code “if($string["errors"][0]["message"] != “”) {echo “Sorry, there was a problem.Twitter returned the following error message:“.$string[errors][0][message].”“;exit();}”
            but it doesn’t work
            Warning: Invalid argument supplied for foreach() in D:rootapitwitter-api-php-masterindex.php on line 22

          • http://iag.me/ Ian Anderson Gray

            Something odd is happening. In order to find out what the issue is we’ll need to do some debugging.

            The argument for the foreach() on line 20 is $string- and this should be array. For some reason it isn’t and is causing a problem. In order to troubleshoot this could you add a line before the foreach line on line 20-

            echo “<pre>”;print_r($string);echo “</pre>”;exit();

            This should print out $string and hopefully tell us what is going on. Let me know what you see- either here or by sending me an email through the contact form. Then I’ll see what I can do to help.

  • Someone :)

    nevermind, just delete my comments, this php script will never work on xampp, but on real server aka web hosting it will work perfectly

    • http://iag.me/ Ian Anderson Gray

      Not tried on a local site, but best to try on a web host. Let me know how you get on. :-)

  • Jason

    I can’t get it to work for other users…it works for the default user with the token, though.

    • http://iag.me/ Ian Anderson Gray

      Hi Jason. Just spotted a problem. The get string wasn’t using the proper username and count field. I’ve updated the final example. Could you try again?

  • Ravi

    I’m facing a problem here. The app only displays my recent tweets inspite of me giving the username and count different. Can u pls help?

    • http://iag.me/ Ian Anderson Gray

      Hi Ravi. Just spotted a problem. The get string wasn’t using the proper username and count field. I’ve updated the final example. Could you try again?

  • Ravi

    Hello Ian. Thanks for the prompt reply! It is not an issue with the username as I’ve tried other twitter user names. The main problem is that when I try to include the “screen_name” and the “count” parameter with the URL itself without specifying the “$getfield” string, I’m getting a “{“errors”:[{"message":"Could not authenticate you","code":32}]}” error. If i just give the normal URL without these parameters and include the “$getfield” string with the username and count parameters, I’m only seeing tweets from my own timeline irrespective of what username I specify.

  • Ravi

    OK. Finally figured it out. In your “$getfield” string, you are passing it as “username”. It should either be “screen_name” or “user_id” and nothing else according to the API Documentation. Just doing this change made it work. Thanks for the tutorial! :)

    • http://iag.me/ Ian Anderson Gray

      Hi Ravi. Thanks so much for pointing this out. Well spotted! I’ve fixed it in the code above.

  • cerebrodigital

    Thanks a lot for this great Tutorial. Exactly what I was looking for.

    • http://iag.me/ Ian Anderson Gray

      Brilliant- glad it helped. Are you working on your own app?

      • cerebrodigital

        :) Yes, still in the basics.
        Im not sure which framework to use. I was thinking using the user system of http://codecanyon.net/item/membership-manager-pro/91421
        Also a bootstrap. But in the other Hand I read that I should use one like Zend, Symfony, CakePHP, Codeigniter, So I dont have vulnerabilities. Is that True?

        • http://iag.me/ Ian Anderson Gray

          Cool. That looks fun. There are a lot of forums and internet discussions with people who say you should this and that. Yes, there are best practices, but at the end of the day you have to work with what you are comfortable with. I’ve read similar discussions and I’ve decided (at least for the time being) to avoid big frameworks. All the ones you mentioned seem to be recommended, but they do require a shift in the way you work and a significant learning curve. However, you are definitely right in saying you will have less vulnerabilities in code if you use tried and tested code from a framework. If you can cope with jumping in the deep end then do. Let me know how you get on!

  • Lester Pereira

    Very good tutorial sir. I ran the same PHP code, the code is running fine but it aint retrieving any data. The output is completely blank. What am I supposed to do here?

    • Lester

      Also I’m using xamp

      • http://iag.me/ Ian Anderson Gray

        Have you viewed source to see if any error messages have been outputted? You could also add ini_set('display_errors', 1); just after the opening <?php to force errors to show. Having said all of that, I am not sure whether this will work locally. Have you tried running it on remote server?

        • Lester Pereira

          I’m getting the following error after running it on the remote server:

          Fatal error: Uncaught exception ‘Exception’ with message ‘You need to install cURL, see: http://curl.haxx.se/docs/install.html‘ in /var/www/tweet/TwitterAPIExchange.php:37 Stack trace: #0 /var/www/tweet/twitter.php(23): TwitterAPIExchange->__construct(Array) #1 {main} thrown in /var/www/tweet/TwitterAPIExchange.php on line 37

          Can you please guide me how to install cURL on win7 32 bit machine?

          • http://iag.me/ Ian Anderson Gray

            Yes, you will need cURL installed, but I am not sure this is going to work locally. I have only ever tested this on a remote server and cURL was already installed. Sorry I can’t help any further with this.

          • Lester Pereira

            This code doesnt run on every machine on the local host for reasons unknown.

            TwitterOAuth by @Ricard0Per — a simple PHP library for API v1.1 worked perfect for me and is recommended

            Link –> https://dev.twitter.com/docs/twitter-libraries

          • http://iag.me/ Ian Anderson Gray

            Thanks, Lester. Sorry this didn’t work out for you. I’ve not tried it locally- it was really designed to run on a web server- particularly since that is always on and you can do some cool stuff with cron jobs to schedule tasks. Hope things work out with the other library.

  • Mitch

    I’m having trouble using this tutorial with the /search/tweets.json. Results will display (via print_r($string)) but I don’t know how to pull various information for it (via looping). Thanks.

    • http://iag.me/ Ian Anderson Gray

      Hi Mitch. This tutorial just covers the basics, but it should work for other Twitter API requests such as the search one (tweets.json). The search results are very similar to the above example so I am not sure why it is returning an array. Can you give an examples?

      • cujophoto

        Ian, Great tutorial that is helpful and well presented. I am having a similar issues is Mitch. I am trying to use the Search endpoint but keep getting an error. I can get the array returned but keep getting an index error in the loop. I am printing the array below the error. You can see the page at http://steventking.com/projects/twitter/app.php and in images attached. Thanks so much in advanced for your help!
        Steven

        • cujophoto

          So, I figured it out not long after posting. Amazing how that happens! Anyway, thanks for your time. To answer the problem, he each loop needs to go one level deeper when using Search endpoint. foreach($string['statuses'] as $items) (see in screenshot).

          Thanks again for the great post!
          Steven

          • http://iag.me/ Ian Anderson Gray

            Ah, ok- cool. Thanks for posting that, really helpful. I had forgotten it went one level deeper for search. I am sure that helps other people. Thanks again!

  • Nate

    Thanks so much, this helped a huge amount.

    • http://iag.me/ Ian Anderson Gray

      Sorry for the age in replying. Glad you’ve found it helpful. Do share what you’ve been able to do with it.

  • Eugene Ivantsoff

    Hm.. I keep getting {“errors”:[{"message":"Sorry, that page does not exist","code":34}]}

    Used your default code from GitHub.

    • http://iag.me/ Ian Anderson Gray

      Hi Eugene, sorry I missed your message. Can you give more details? Did you manage to sort it in the end?

  • Edwaldo

    Ian, good afternoon! I am Brazilian and I am using your tutorial and found an error. Looking at the reviews of other users realized that this application to work should not be performed on localhost. However, do not own a domain which can test, would make some adjustment for use in localhost?

    I thank you for the attention!

    • http://iag.me/ Ian Anderson Gray

      Thanks for your comment, Edwaldo. I’ve not tested this on localhost, but as the others have said it appears that the script doesn’t work on localhost. The issue will be with the PHP Wrapper script itself, and a similar question was asked in this issue on GitHub- https://github.com/J7mbo/twitter-api-php/issues/15

      Having said that, can you make sure that your local PHP installation has got the cURL library installed? The Twitter PHP Wrapper script requires this to work.

    • Edwaldo

      Ian, once again thank you for your cooperation. ‘ll Be looking if I can make the operation of the application.

      Congratulations tutorial and have a good afternoon!

      • http://iag.me/ Ian Anderson Gray

        Great- let me know how you get on!

  • Franko

    Very helpful. Thank you very much. I’m proud for my firs API calls :) Now I need to read documentation to try other

    • http://iag.me/ Ian Anderson Gray

      Thanks, Franko. Glad you’ve found it helpful. Once you get started you’ll realise all the other cool things you can. Read the docs and let me know how you get on. You could also have a look at my app, Twools, which shows you the kind of stuff you can do with the wrapper script.

  • John Baggs

    Brilliant tutorial, Ian! Clearly written, and just at the right level for a PHP n00b like me. Only problem is that it wouldn’t work for me… :( … I just copied and pasted your code, and added my twitter keys. It is at http://baggs.org/twitter/iag/littleApp.php — my PHP config seems OK too, see http://baggs.org/twitter/iag/info.php. Could you try to help, please? (If it helps, I’ll email you my cPanel and dev.twitter logins. Of course I’ll trust you! You’ve a reputation to keep up!) Many thanks in advance, John.

    • http://iag.me/ Ian Anderson Gray

      Hi John, sorry for the delay in getting back to you. I’d be happy to help. Looks like there is some server or script issue as it’s causing a 500 error. Probably best if you get in touch via my contact form. Then I can try and help you. Thanks!

      • John Baggs

        Hi Ian,

        I fixed it with a programming technique I invented many years ago:-

        (1) Add debugging code. [The app will now work properly.]
        (2) Remove debugging code. [The app will still work properly, despite being back to the original non-working code.]

        This proves that software is not science. It is superstition!

        It is working (for me at least) (for now anyway) at:-
        http://baggs.org/twitter/iag/Test6.php?user=barackobama&count=3

        I was previously thinking about offering to PayPal you the price of a couple of drinks for a little more advice. But I see that since your last reply, you have added an HonestyBoxx. Do I take it that that is what you refer to as your contact form, and that you are now looking for serious money (which no doubt you fully merit, but which some of us may not be able to afford right now)?

        Best regards,

        John

        • http://iag.me/ Ian Anderson Gray

          Hi John. You’re right, software is not science- I think it’s an art with a life of its own. Love your technique. Have you thought of patenting it? You could make a fortune! ;-)
          Have you thought what you’re going to do with your app now that you’ve got it working? I’d love to know.

          That’s very kind of you to donate something for a few drinks. Well spotted seeing the HonestyBoxx- it was only there for half an hour as I was having a play with it. I was going to add it to me next design of the site for next year, but I may as well add it now. My concern was that it wasn’t obvious what it was. I wasn’t looking for serious money, but just experimenting to see if getting paid to answer questions might be an interesting revenue stream! Anyway, don’t feel like you have to do anything, it’s just good that you’ve managed to get it working. If you have any other questions do let me know!

          • John Baggs

            Hi Ian,

            Ahhh… Drinks… And you like single-malt whiskies too… There’s good news, and there’s bad news…

            The good news is that it just so happens that I’ve got £500+ worth of single malts, just waiting for a drinker. Morrisons were doing a promotion on quality drinks, and selling single-malts at wholesale prices. So I went mad and bought a selection at Asda instead. With Asda’s 10%-cheaper guarantee, I got them cheaper than wholesale. Now I’ve got Ardmore, Bowmore, Glenfiddich, Glenlivet, Glenmorangie, Glen Moray, Jura, Laphroaig, Macallan, Talisker, etc, etc. All in unopened bottles (too good for the likes of me to drink!) and just waiting for a special guest to sample them.

            The bad news is that you are in Cheadle (not too far from my first university at Keele). The drinks are in Southampton, over 200 miles away…

            My proposed App is still very much at the feasibility stage. The idea is to promote a children’s charity via Twitter. The charity has narrow aims. It is for the children of professional parents who are at private schools. When the parents die, or fall ill, or suffer other financial misfortune, and school fees cannot be paid, the schools are usually completely ruthless about ejecting the children. The Charity Commission has recently expressed concern about the large number of private schools which are nominally charities (to avoid tax) but which in fact do very little that is actually charitable. Having to change schools, especially when near exams, often leads to missing the chance of attending university and a subsequent professional career. It really can blight young lives.

            Persuading people to donate to charity often requires a lot of personal interaction, which would in this case be by tweets individually written for each prospective donor. Charity workers have limited time, which must be used on the very best prospects.

            Stage 1 would be to start with twitter users known to actively support charities. From these ‘seeds’, the App would explore their networks of friends and followers for likely prospects (e.g. by elimination of people who don’t speak ‘en’ or ‘en-gb’), and do this recursively. Stage 2 is to rate our prospects on a points system, e.g. by having large and genuine twitter networks, or by having keywords like ‘father’ or ‘mother’ in their bio’s, or by having ‘school’ or ‘charity’ in their tweets. Stage 3 would be to narrow down the very best prospects, and to assign them to the best charity workers (e.g. by common interests, or by living locally) to pursue.

            It may be a long way to go, before I even know whether it will be feasible at all! And I am still a n00b at API’s and PHP, although PHP isn’t too hard to learn as I previously programmed in C++.

            My next test App is to graduate from your App showing a user’s tweets, to one inspecting a user’s followers. It is to inspect a user with 50k+ followers, and to report how many of his followers fulfill the criteria of having (a) 2k+ followers of their own, (b) having a bio at least 50 characters long, and (c) having ‘en’ in their language. It will then store them in an array, sort the array by number of followers, and print the top 100.

            I’ll ask for your help with the problems. (There will be problems!)

            Best regards,

            John

          • http://iag.me/ Ian Anderson Gray

            John, it’s a shame you can’t digitise single malt whisky. I’m impressed with 3D printers, but not sure that they’d cut it for this purpose! :-)

            The idea for your app is an interesting one. I didn’t realise that there was a big issue with private schools ejecting children for financial reasons.

            I hope my simple app helps. You might want to have a look at Twools, which is my Twitter app based on the above. I’ve written about it on my blog and you can see the documentation at http://twools.it/ – it’s something I want to develop more but I just lack the time.

            With your next stage, you may need to cache the responses and run the script on a schedule. If you’re looking through a user’s 50k followers, you’ll go through your allocated requests easily under the 15 minute slot. You could always test for the “rate exceeded” error message and then start up again in 15 minutes. Let me know how you get on!

            Ian

          • John Baggs

            Hi Ian,

            It’s an awful confession, but I don’t know a thing about 3D printers. Are they really useful?

            Your tutorial was a tremendous help in getting me started. The official Twitter docs are only comprehensible if you already know what you are doing!

            At the moment, my App can inspect a user’s followers, filter by my criteria, and report the results.

            Testing is very difficult with Twitter’s limits of 15 calls per 15 minute window. Especially when it seems in real life more like 14/15 calls per 19/20 minute window!

            Next step is to call it with cron, and get it number-crunching 24/7.

            All the best,

            John

          • http://iag.me/ Ian Anderson Gray

            Hi John. It’s not an awful confession. The only reason that I know about 3D printers is because we’ve discussed them at Cheadle Geeks which is the monthly tech meet up I organise. I haven’t seen them in action but they are definitely the future!

            The Twitter docs are very badly written- they assume a lot of knowledge and are difficult if you’re just starting out. That’s why this PHP wrapper script is so useful- it makes it a lot easier.

            Cron sounds good. Looking forward to the next update!

  • Brazil

    Thanks man, you’re the best!

    • http://iag.me/ Ian Anderson Gray

      Aww, thanks- very kind! Have you built an app yet?

      • Brazil

        Yes! – First, sorry for my english =p, you could do a tutorial on how to do and to authorize the application callback for Oauth, I tried to create one with Abraham but it still fails. And also follow any Twitter account by API or Oauth. Thanks for listening =)!

        • http://iag.me/ Ian Anderson Gray

          Your English is great! :-)
          The PHP wrapper for Twitter doesn’t use OAUTH as “Sign in with Twitter”- it was built to be a simple script and so you have to create an app at dev.twitter.com- so you don’t have to worry about callbacks. The thing I love about the script is once you’ve set it up it can run in the background and you could even run it on a schedule.
          What do you mean by follow any Twitter account? Do you want a kind of auto follow back?

  • Alejandro Oñate Latorre

    I have tried this script with the default application that comes and says,

    message: “Sorry, that page does not exist”
    code: 34

    But this is not what I’m worried because there may be some typographical errors. I tested the application that I wanted:

    $ url = “https://api.twitter.com/1.1/search/tweets.json”;
    $ getfield = ‘? # q = baseball & result_type = recent’;

    And it gives me a much worse mistake. The answer I get is:

    message: “Could not authenticate you”,
    code: 32

    I created a Twitter Application of the data, as I am doing tests on my computer, I used as http://127.0.0.1/ URL correctly copy the 4 tokens required for access..

    That does not happen. Can I get help? Thank you.

    • http://iag.me/ Ian Anderson Gray

      Sorry for the issues you’ve been having. I’ve not tried the script locally- it is designed to run on a web server from what I’ve read. I do know that other people have tried it locally and it does not work. Can you try it on a web server and let me know how you get on?

  • Carlus

    hi, using your code on PHP 4.4.9 I obtain always this error:

    syntax error, unexpected T_OBJECT_OPERATOR, expecting ‘,’ or ‘;’ in /home//public_html//littleApp.php on line 21

    The line 21 is:
    ->buildOauth($url, $requestMethod)

    How can I resolve? many thanks!

    • http://iag.me/ Ian Anderson Gray

      That’s odd. I haven’t tested in that version of PHP, but I don’t see any reason why it wouldn’t work. There is obviously some missing or stray comma or semi colon somewhere in your code. Could you send me your code (use my contact form above) so I can have a look? Obviously remove the oauth tokens.

  • http://trki.sk/ Lukas Lukac

    Just what i was looking for! awesome man… written nicely, precisely, without any try of confusion. Thx

    • http://iag.me/ Ian Anderson Gray

      Thanks, that’s what I was trying to do with the article. Hope you manage to write something awesome!

      • http://trki.sk/ Lukas Lukac

        not yet i was just looking for my options but hopefully i will! :)

  • disqus_xieoHrZfHH

    Working fine on localhost too. Thanks.

  • Will

    {“errors”:[{"message":"Bad Authentication data","code":215}]}

    • http://iag.me/ Ian Anderson Gray

      Hi Will. Could you double check that you’ve entered your OAUTH key etc correctly? Also check at dev.twitter.com that everything is as it should be. Twitter is having trouble authenticating you with the app you registered.

  • Dreysha55

    Like some other I see here, I had trouble with it on wamp/localhost. But fixed it!
    Here how:

    1) enable you curl: from the config file or simply right-click the wamp icon, go to php, php-extensions, check “php_curl”

    2) if you get a blank page
    – open the “TwitterAPIExchange.php” provided here
    – right after

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);

    - to be able to read what the error is, add this before curl_close($feed);

    if($json===FALSE){ echo “Curl error #”.curl_errno($feed).”:”.curl_error($feed); }

    - I had: “Curl error #60 SSL Certificate: unable to get local issuer certificate”. I checked and true, I didn’t even have one. I guess my package doesn’t come with one. so I specifically added one!

    3) To add, go to http://curl.haxx.se/docs/caextract.html
    - download the cacert.pem and save it where your server php folder is. i’ve put mine in c:/wamp/bin/php/php5.4.16/cacert.pem
    -PS, beginners, if you’ll copy/paste the cacert file into notepad make sure you save the extension as cacert.pem and not cacert.pem.txt. It’s a big difference

    4) Now link you certificate to your php.
    - open php.in and add: curl.cainfo = “C:/wamp/bin/php/php5.4.16/cacert.pem”
    - I’ve put mine at the end of the file

    There! Now it works from localhost! Hope this helps someone.. :D
    PS: Never ever get lured into turning off CURLOPT_SSL_VERIFYPEER. There’s always another way! :D

    • http://iag.me/ Ian Anderson Gray

      I just wanted to reply to say a massive thanks! I haven’t had the chance to properly take in what you’ve said here, but at first reading it makes sense. As I have mentioned in replies to other comments, I haven’t tested this script locally- I have just used it on my web server. I really should add a note about making sure that cURL is installed. My first thought is that we should add a line at the top of the script to check that cURL has been installed and spit out a helpful error if not.
      To be honest I am a bit confused about what you’ve said about the SSL certificate. I don’t have one on the website I’ve installed this script on, but perhaps you’re talking about something else? Can you explain? Thanks again!

      • Dreysha55

        Oh I should thank you!!! This is the most comprehensible stater tutorial I’ve stumbled upon!! Can’t wait to make more complex apps!

        Your error catcher perfectly worked! It did inform me that I didn’t have Curl! That’s how I even got to enable! The error catcher I added gives a reply after that from twitter. Yes, now it requires SSL/TLS connection, since January 14 2014. Saw the notification when I logged into my developer’s account. You can read it here: https://dev.twitter.com/discussions/24239

    • Houssemaster

      hey Dreysha how you added the certicaficate cause i have the same problem

      • Dreysha55

        I simply saved it in my server (chose my php folder) then added a reference to it via php.ini (with curl.cainfo). The steps listed above are “exactly” what I did. Where are you lost? What is it that didn’t work for you?

  • michael

    Great tutorial. It would be useful to cache the data in option. Per default the information is cached for 5 minutes by the API but to be able to increase it would be great, because of the rate limit.
    Does anyone know how to code that?

    • http://iag.me/ Ian Anderson Gray

      Thanks. Caching is definitely a good thing, and I’ll be looking at doing just that in another tutorial (hopefully soon!)
      I’ve already built that into my Twitter app, Twools (Read more here). The way I did it was to save the returned JSON from the Twitter API request to a file. The next time the script runs, it checks to see how old that file is, and if it is less than the cache time you want, it uses the cached file. If not, it asks for a fresh request from Twitter.
      As you can see, I didn’t want to add this complexity to this introduction to building a Twitter app script!

  • Matt Garvin

    This is a great article — clearest I have found on this topic. Like some others, I am getting the “Warning: Invalid argument supplied for foreach() in…” error, and adding the bit to show twitter errors didn’t help.

    I am testing it on a live site, so there is no localhost issue. And I have checked the oAuth variables for accuracy many time.

    Any ideas?
    Matt

    • http://iag.me/ Ian Anderson Gray

      Thanks, really glad to hear it has helped.
      However, sorry to hear that you’ve had problems. Firstly it looks like you’ve got PHP error reporting set to the highest level (which includes minor notices). It’s best to switch that off. You can do that by putting error_reporting(0); at the top.
      Having said that, the reasons you were getting those notice errors was my fault! You were using the line I included in one of the earlier comments, but I had forgotten to put quotes round the names in the array. I’ve added the error message line to the article and to the script on GitHub, so please use that!

      Hopefully once you’ve done that, you’ll be able to see if Twitter is returning an error. That is likely, because you are getting an Invalid argument supplied for foreach() error. That means that foreach isn’t getting an array as expected.

      Let me know how you get on!

      • Matt Garvin

        Wow, thanks for the fast response! So I went to github and grabbed the “littleApp.php” and “TwitterAPIExchange.php”. That is all I need, right? Left the API file as is, but changed the oAuth variables to my own in “littleApp.php”, and changed the $user = to the correct user in line 12.

        I put it all in the root of a live site, and now get
        Warning: Invalid argument supplied for foreach() in littleApp.php on line 20

        So… not getting on well, but I really appreciate your assistance!

        • andy

          hi matt, i have the same problem, have you solved it yet?

          • http://iag.me/ Ian Anderson Gray

            Oops, I just realised I never responded. So sorry about that.
            This is a little odd. the argument for the foreach() on line 20 is $string- and this should be array. For some reason it isn’t and is causing a problem. In order to troubleshoot this could you add a line before the foreach line on line 20-
            echo “<pre>”;print_r($string);echo “</pre>”;exit();

            This should print out $string and hopefully tell us what is going on. Let me know what you see- either here or by sending me an email through the contact form. Then I’ll see what I can do to help.

  • Rameez

    Hi Ian, When i tried this script i got an error in this line ->performRequest(),$assoc = TRUE);

    Since I am new to PHP i was not able to debug the same, can you please help me to solve the same, I am using PHP 5.5.6

    • http://iag.me/ Ian Anderson Gray

      Hi Rameez. That’s odd. As I have said elsewhere I haven’t tried this on localhost, and I haven’t tried it on PHP5.5, but I see no reason why it shouldn’t work. Is line 16 this line for you:
      $string = json_decode($twitter->setGetfield($getfield);
      ?
      Wasn’t sure what the phpfiddle.org link meant?

  • Henrik Bank

    Great tutorial. Is it possible to somehow strip the URL in a tweet – in order to make the url active and format it. ?

    • http://iag.me/ Ian Anderson Gray

      Hi Henrik. I wanted to make this article really simple, so it doesn’t go beyond outputting tweets in a very plain way. What you ask goes out of scope of the article, but you could check out this answer on Stack Exchange- http://stackoverflow.com/questions/5341168/best-way-to-make-links-clickable-in-block-of-text
      You’d need to use the function given in the answer to output the tweets with clickable links. I do plan on writing follow up articles, so hopefully I can address this then. Ian

  • http://scoop.it Guillaume Decugis

    Hey Ian: awesome stuff and exactly what I needed. Thanks!

    I noted a minor error on line 13 of your final version of the script:

    if (isset($_GET['count'])) {$user = $_GET['count'];} else {$count = 20;}

    should be:

    if (isset($_GET['count'])) {$count = $_GET['count'];} else {$count = 20;}

    Shouldn’t it?

    Again, awesome tutorial and works like a charm: thanks!

  • http://www.mynoblecare.com/ Usama Ejaz

    Really nice article. This helped me. Thanks! Now going to create an awesome app ;)

    • http://iag.me/ Ian Anderson Gray

      Thanks, Usama. Really glad it helped you- that’s what I love doing. Can you please come back here once you’ve created your awesome app and tell me how you got on?! Thanks!

      • http://www.mynoblecare.com/ Usama Ejaz

        Yes, why not :) It would be great for me to share! Till then, a lot of development to do ^_^

  • http://www.creativepearson.com Dave

    Thanks for this walkthrough, how can you make the links within tweets active?

    • http://iag.me/ Ian Anderson Gray

      Hi Dave, yes you can, but it was out of scope of this beginner’s tutorial. I came across the following function which I would add at the start of the above script:

      // The function that links the hashtags, urls and usernames into links…
      function twitterize($raw_text) {
      $output = $raw_text;
      // parse urls;
      $output = preg_replace(‘@(https?://([-w.]+)+(/([w/_.]*(?S+)?(#S+)?)?)?)@’, ‘<a href="$1" target="_blank">$1</a>’, $output);
      // parse usernames
      $output = preg_replace(‘/@(w+)/’, ‘<a href="http://twitter.com/$1&quot; target="_blank">@$1</a>’,$output);
      // parse hashtags
      $output = preg_replace(‘/s+#(w+)/’, ‘ <a href="https://twitter.com/search?q=%23$1&quot; target="_blank">#$1</a>’, $output);
      return $output;
      }

      Then you can run the tweet through that function by changing line 23 to the following:

      echo "Tweet: ". twitterize($items['text'])."<br />";

      Hope that helps.

  • Pratik Ghela

    Hey Hi,

    The code worked excellent. The only issue is that the hash tags and user profiles are not linked.

    Thanks!

    • http://iag.me/ Ian Anderson Gray

      Thanks, glad you found it helpful. With regards to making the hashtags and screen names as hyperlinks I gave an example in the comments below. I didn’t include it in the article as it is beyond its scope.

      Hi Dave, yes you can, but it was out of scope of this beginner’s tutorial. I came across the following function which I would add at the start of the above script:

      // The function that links the hashtags, urls and usernames into links…
      function twitterize($raw_text) {
      $output = $raw_text;
      // parse urls;
      $output = preg_replace(‘@(https?://([-w.]+)+(/([w/_.]*(?S+)?(#S+)?)?)?)@’, ‘<a href="$1" target="_blank">$1</a>’, $output);
      // parse usernames
      $output = preg_replace(‘/@(w+)/’, ‘<a href="http://twitter.com/$1&quot; target="_blank">@$1</a>’,$output);
      // parse hashtags
      $output = preg_replace(‘/s+#(w+)/’, ‘ <a href="https://twitter.com/search?q=%23$1&quot; target="_blank">#$1</a>’, $output);
      return $output;
      }

      Then you can run the tweet through that function by changing line 23 to the following:

      echo "Tweet: ". twitterize($items['text'])."<br />";

      Hope that helps.

  • Pingback: How to grow your business with Twitter – part 5 | Monitor Everything IT: Website, Server, Application, Network. 100% Free!Monitor Everything IT: Website, Server, Application, Network. 100% Free!

  • Brunno Arthur

    Friend, congratulations!

    I’m just a question … How do I get links to my tweets appear as a link?

    thank you

    • http://iag.me/ Ian Anderson Gray

      Hi Brunno. I didn’t explain that in the article because it was out of scope. However a few people have already asked that and I included the code. See below!

  • Houssemaster

    Hi everyone, i have a big trouble and i can’t solve it, this code returns ” Invalid argument supplied for foreach()”. i’m using wamp server 2.2with php 5.3.10 on windows 7 , please help me i need it very well (sorry for my poor english)

    • http://iag.me/ Ian Anderson Gray

      Sorry to hear you’ve had problems with this. I’ve not been able to test this, but it seems that the PHP wrapper doesn’t work locally. The best way would be for you to use a web host. Could you try that and see if it works?

      • Houssemaster

        Hi Anderson, i would like to think for this good tutorial because it helped me, now for the troubles i have found some solutions to work locally (with wampserver) so i suggest to you to add what i will tell you in your tutorial:

        1-enable the curl biblio : right-click the wamp icon, go to php, php-extensions, check “php_curl”

        2-enable the ssl certificate: right-click the wamp icon, go to php, php-extensions, check “php_openssl”
        3- create file with name=”cacert” and save it in .pem extension (cacert.pem) you can download this file file from my dropbox https://www.dropbox.com/s/0rc10a1f9clmpef/cacert.pem

        PS: you need to remember the path of this file because you need it later

        4-add to the TwitterAPIExchange file provided here those lines(after $feed = curl_init();):

        curl_setopt ($feed ,CURLOPT_CAINFO, “C:/wamp/www/twittercacert.pem”);
        curl_setopt_array($feed, $options);
        $json = curl_exec($feed);
        if($json===FALSE){ echo “Curl error #”.curl_errno($feed).”:”.curl_error($feed); }
        curl_close($feed);

        5-add to php.ini this line (in the end of the file): curl.cainfo = “C:/wamp/www/your own repertory/cacert.pem”

        i hope i don’t missed anything :)

        • http://iag.me/ Ian Anderson Gray

          Thanks for detailing it here, I am sure this will be of help to people who want to run this locally. Ian

  • http://infomundo.org/ Infomundo

    Thanks very much. Can you explain how to use friendships/lookup? Thanks a lot. It is for a web call – infomundo.org

    • http://iag.me/ Ian Anderson Gray

      I haven’t used the friendships/lookup call myself yet. I assume you’ve looked at the documentation here – https://dev.twitter.com/docs/api/1.1/get/friendships/lookup

      In the $getfield above you’d need to send the screen names of all the users you want to look up the relationships for.

      For example:

      $getfield = “screen_name=iagdotme,twitter,boagworld,baritoneuk”;

      You’ll then get the data returned as JSON which will be converted in to an associated array. You should then be able to play around with the data. As it says in the documentation, it’s the connections you want to look for. They will be set as: following, following_requested, followed_by, none, blocking or muting.

      Hope that helps.

  • Nirdesh Shukla

    Please help me i am not able to run these scripts. I have tried hell lot of times but havent really been able to install or work with curl.

    Please help me in working with this by a detailed step by step procedure.

    Thanks in advance!!!!!

    • http://iag.me/ Ian Anderson Gray

      Sorry about the trouble you’re having. Are you doing this locally or on a web server? To be honest I just asked my hosting provider to install cURL but it depends on your hosting package. If you could give us more information about your hosting environment hopefully someone here can help.

  • Rob

    Hi, great tutorial! thanks for sharing. I have only one issue – this is returning my retweets as my tweets, can they be displayed via this with owner’s name etc? How could i do that? thanks!

    • http://iag.me/ Ian Anderson Gray

      Thanks, Rob. I’ve not tested this. If you want to not include retweets, then you can add include_rts=false in the $getfield string. This tells Twitter to not include native RTs.

      For example, update links 14 to:
      $getfield = “?screen_name=$user&count=$count&include_rts=false”;

  • Anubhav

    it doesn’t work…..”syntax error, unexpected ”oauth_access_token secret” (T_CONSTANT_ENCAPSED_STRING), expecting ‘)’ “……….i m getting this error…

    • http://iag.me/ Ian Anderson Gray

      You’ll need to check the code. Sounds like you’ve got a stray bracket i.e. “)

  • Tommy

    Hi, thank you for great tutorial, it works perfectly! But I have one additional question: how can I display images (photos) in tweets? I have read something about Entities in Tweets in Twitter Documentation but I don’t understand it and I don’t understand how to make it work… Can you help me, please? Thank you!

    • Tommy

      update – I figured it out, problem solved :)

      • http://iag.me/ Ian Anderson Gray

        Please do share what you found out here if you get the chance! Others might find it useful.

  • Anurag Prabhakar

    I believe I did everything as mentioned here, but still when I click on the TwitterAPIExchange.php file, I get nothing Below are the screenshots of my wrapper.php and the website I’m hosting the php files on. TwitterAPIExchange.php is the same as downloaded from github, and necessary changes in access tokens, consumer keys etc. have been made. Please help me out! I’m stuck.

    • http://iag.me/ Ian Anderson Gray

      I’m not sure about your host, but reading the text above it says you need to remove the file default.php before uploading your website. I would have thought just removing default.php should do the trick.

      Is the file you are using to test called test.php? Have you viewing that?

      • Anurag Prabhakar

        Deleting default.php didn’t change anything. test.php is just a 3 line php code to display “Simple php test” on the webpage. It works fine, but with just 2 files (wrapper.php and TwitterAPIExchange.php) too I get a blank page on clicking TwitterAPIExchange.php.

        Btw, which site did you host your files on ? Should I try a different host ? (I tried localhost but couldn’t get it working)

        • http://iag.me/ Ian Anderson Gray

          What is wrapper.php? Is that your test file? You won’t want to click on TwitterAPIExchange.php- that won’t do anything by itself. Have you tried the example littleApp.php script above? Your host shoudl work, assuming you have a modern version of PHP and have cURL installed. If you don’t have cURL installed, it should give you an error- not a blank page. You could try a different host, but it would be good to know what the problem is before switching.

          • Anurag Prabhakar

            I’ve posted the code in wrapper.php in the first comment (as an image, click on “see more”). I have curl installed. “curl –version” return this – “curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3″. And as I said, I’m getting a blank page, no errors.

          • http://iag.me/ Ian Anderson Gray

            Is that all the code in wrapper.php? If so, it won’t output anything because there isn’t anything to output. Could you try and copy the example I gave above. You need to initiate the API request:

            $twitter = new TwitterAPIExchange($settings);

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

            and then you need to output what you want based on the data in $string. The example I gave above, goes through the results and outputs them:

            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 />";
            }

  • Wasiq Muhammad

    Having an error not working properly Warning: Invalid argument supplied for foreach() in /home/a5771514/public_html/home.php on line 20 error

    • http://iag.me/ Ian Anderson Gray

      Hmmm, the foreach is expecting an array to loop through, and it isn’t getting one. Before the foreeach line can you add the following:

      printr_($string);exit();

      This should output what is in $string and give us an idea of what the problem is.

      • Tyler_Hakes

        Hey Ian, I am having this same issue. I’m not working locally, but rather have it uploaded to my server. I have to guess that it has something to do with my server config as I am copy and pasting your exact code and using the PHP file directly from Github.

        When I add the line that you mention here, I get nothing. I’m currently getting an error from the array as noted above.

        See: http://twitter.tylerhakes.com/GetTwitterStuff.php (I’m echoing stuff on either side of the output, trying to debug)

        Any ideas?

        • http://iag.me/ Ian Anderson Gray

          Hi Tyler, could you add the printr_($string);exit(); as I mentioned above (just before the foreach() line? That should help to show what the problem is.

          foreach is expecting an array of your Twitter data but it’s not getting that. This is why you are getting a warning, Invalid argument supplied for foreach()

          If you can do this, I’ll try and help you sort it out.

          • Tyler_Hakes

            Ian, I have added that line previously, but nothing happens. I just get a blank output.

          • http://iag.me/ Ian Anderson Gray

            OK, that means that Twitter isn’t returning anything or that the script isn’t decoding the JSON output. Could you try one more thing? After

            $twitter = new TwitterAPIExchange($settings);

            put the following:

            echo $twitter->setGetfield($getfield)
            ->buildOauth($url, $requestMethod)
            ->performRequest();

            exit();

            basically we’re creating the script as of step number 6 above. I want to know if Twitter is returning the JSON. If you are still getting a blank output then Twitter isn’t returning anything and we’ll have to do some more troubleshooting.

            By the way, do you know if you have cURL in your hosting environment. The wrapper script needs this, but it should give you an error if it isn’t available. If in doubt ask your host.

          • Tyler_Hakes

            Hi Ian, thanks for the help. I am still getting a blank page with that code. I spoke with support at my host (MedaTemple) and they assured me that cURL should be setup already. I also checked my error log to see if it had anything, but there’s nothing new in there or at all related to this.

            I’m quite stumped now. I’m copying everything as it’s shown here — only changing my API keys.

            Any more thoughts? I appreciate you taking the time to help me troubleshoot this.

          • http://iag.me/ Ian Anderson Gray

            Hi Tyler. Well the fact that it still outputs nothing shows us that Twitter isn’t returning anything or that there is a problem earlier on in the script. It shouldn’t be anything to do with your API keys because if there was a problem, Twitter would give you an error. If you’d like me to troubleshoot further the only way would be for me to have a closer look. If you’re happy for me to have a look then contact me via my contact page. If you could give me temporary FTP access I could see if I can find the problem. If not, maybe others can help?

  • http://www.usacustomers.com usa customers

    how can we make it auto favorite?

    • http://iag.me/ Ian Anderson Gray

      That’s out of scope of this beginners’ article and bulk automation of favoriting is probably against Twitters’ terms and conditions. However, you can favorite a tweet using the following API call: https://dev.twitter.com/docs/api/1.1/post/favorites/create

      This requires that you use the POST method. I do hope to write a second article which goes into more detail.

Ask me a Question!