I’ve been getting some emails lately asking for a tutorial or a guide on how to integrate the Twitter API into a website using PHP. The Twitter documentation does a decent job in helping as to guiding you in the direction to take for development, and the PHP functions you should be using to make the request to Twitter. I’ve taken my time to write out a little guide on how to work with these functions, and how to make a request to Twitter’s web service using several features of PHP 5.
Step 1 – Choose a Method
Go to the Twitter API Wiki and choose a method you want. Most likely, you would probably want to fetch your current timeline. The method you want to be using is statuses/user_timeline. This method, from the description provided by Twitter, will return the 20 most recent status posted by a given user.
Step 2 – Choose a Return Format, and HTTP Method
For this tutorial, we will be using XML since PHP5 has a built-in class (DOMDocument) that can read XML easily in which we will be using later. There is only 1 HTTP Method which is “GET” so that’s pretty much set.
Step 3 – Build the Request URL
Now that we have our desired format, and method, we can proceed to the next step which is building the URL in which we will make our request to. From, the documentation, the method’s request URL is “http://twitter.com/statuses/user_timeline.format“. The method allows us to retrieve data with our Twitter ID, or our account name and since the account name is easier to remember, let’s add it to our request URL. The parameter for the Twitter account name is called “screen_name”. Appending it to the URL will look like so below:
http://twitter.com/statuses/user_timeline.xml?screen_name=tranvu
To check if your request URL is correct, try going to that URL with your web browser. Assuming your browser is up to date and can view XML files, you should be seeing the XML response from that URL with the latest status. If there’s a popup asking you for a login, then you must authenticate yourself to be able to view the data. (We won’t be covering authentication in this tutorial).
You can further play around with the data more with the parameters from the documentation page such as setting the limit of how many status to receive, the page of results, etc. For this tutorial, we won’t be using any of these extra parameters.
Step 4 – Making the Request to Twitter
There are several ways to do this. I recommend using cURL to make the request and DOMDocument to parse the data. You can also skip the cURL and just use DOMDocument to make the call also, but not recommended. I’ll show you both way in which you can do this.
Making the request with DOMDocument
$url = "http://twitter.com/statuses/user_timeline.xml?screen_name=tranvu"; //Your request URL from step 3 $dom = new DOMDocument(); //instantiate the DOMDocument object $dom->load($url); //the DOMDocument object calls it's class method to load the URL
Line 1 is basic PHP which you should understand. Line 2 and 3 deals with object-oriented programming (OOP). Line 2 creates a new variable called $dom which is set to hold the DOMDocument object. I will skip the details on OOP and cut to the chase. Line 3 calls the object’s class method load() in which passes the $url through the parameter. The load() method takes 1 argument, which is a filename. The URL counts as a filename so we are able to use the URL directly.
Making the request with cURL
$url = "http://twitter.com/statuses/user_timeline.xml?screen_name=tranvu"; //Your request URL from step 3 $ch = curl_init(); //starts a cURL session curl_setopt($ch, CURLOPT_URL, $url); //the URL to make the request curl_setopt($ch, CURLOPT_HEADER, 0); //don't return the header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return as a string instead of echo-ing it out directly $res = curl_exec($ch); //executes the cURL session and store it into a variable curl_close($ch); //remember to close to free up memory $dom = new DOMDocument(); //instantiate the DOMDocument object $dom->loadXML($res); //loads the response to the $dom object
As you can see clearly, the second method is longer in coding. I prefer the cURL method because it gives me the ability to set extra options when making the request such as including the headers, changing the request to a POST request instead of a GET, etc. There are plenty of other options that you can take advantage of when making a request with cURL as to compared doing it with just the DOMDocument load() method.
Step 5 – Testing the Data
If you have did everything correctly thus far, you should have no problem outputting the data to the browser. To test this, try doing this step below:
echo $dom->saveXML();
The above method saveXML() will return a string of the XML tree that has been loaded into the object. Since we are echo-ing out that string, you should be see a bunch of jargon in your browser. You can also check the source code and make sure the XML source is valid and is what you are looking for. It should look similar to the one on the Twitter’s documentation page.
Step 6 – Parsing the Data
Once you have verified that the data is what you want, you are ready to parse the data using PHP’s DOMDocument object.
From the loaded XML tree, you would want to fetch each “status” element. To do this, we will use the getElementsByTagName() method.
$statuses = $dom->getElementsByTagName('status'); //fetches all status element in the XML.
The line above will fetch all element with the tag name as “status” and stores it into an array called “statuses”. We can now use a for loop to further dissect the tree.
foreach($statuses as $status) { $created_at = $status->getElementsByTagName('created_at')->item(0)->nodeValue; //fetches the "created_at" tag's value and store it into a variable $text = $status->getElementsByTagName('text')->item(0)->nodeValue; //fetches the "text" tag's value and store it into a variable echo $created_at." - ".$text." \n"; }
Line 2 and 3 does the same thing. Both retrieves data and stores it to a variable. Using the getElementsByTagName() method again, but this time instead from the $dom level, we want it from the $status element level. We want to retrieve the tags “created_at” on line 2 and “text” on line 3. Because there are only one node named like so under the status element, the item() specifies that one node specifically. “nodeValue” is a property of item(0), which in turn is the node that we want. If this is too confusing, you may want to read up a bit on the document object model (DOM) and XML as it will help you better understand the whole tree structure.
Line 4 basically echo’s out the 2 variables we have set and the loops continue for each status that is in the XML tree.
Step 7 – Putting it all Together
Combining what we have done so far, we will get something like so below:
$url = "http://twitter.com/statuses/user_timeline.xml?screen_name=tranvu"; //Your request URL from step 3 $ch = curl_init(); //starts a cURL session curl_setopt($ch, CURLOPT_URL, $url); //the URL to make the request curl_setopt($ch, CURLOPT_HEADER, 0); //don't return the header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //return as a string instead of echo-ing it out directly $res = curl_exec($ch); //executes the cURL session and store it into a variable curl_close($ch); //remember to close to free up memory $dom = new DOMDocument(); //instantiate the DOMDocument object $dom->loadXML($res); //loads the response to the $dom object $statuses = $dom->getElementsByTagName('status'); //fetches all status element in the XML. foreach($statuses as $status) { $created_at = $status->getElementsByTagName('created_at')->item(0)->nodeValue; //fetches the "created_at" tag's value and store it into a variable $text = $status->getElementsByTagName('text')->item(0)->nodeValue; //fetches the "text" tag's value and store it into a variable echo $created_at." - ".$text." \n"; }
Make sure you don’t forget to enclose the code in PHP open and end tags to make sure the server parse the code as PHP. If everything is correct, it should output like something below.
Mon Jun 08 22:13:14 +0000 2009 - more stuff to do for LCLA! Sun Jun 07 23:56:49 +0000 2009 - doing some minor seo changes to my website. Sun Jun 07 21:18:29 +0000 2009 - RT @Lakers: RT @Jbuss: Twitter Game Day Chant: Let's Go @Lakers! (keep it rolling) Sun Jun 07 21:15:25 +0000 2009 - RT @bkmacdaddy: 35 Awe Inspiring Website Designs - http://bit.ly/oQCcp #webdesign Sun Jun 07 08:17:47 +0000 2009 - check out http://thinksimilar.com/ Sun Jun 07 02:31:47 +0000 2009 - I am about to embark on a new redesign for a friends record label. Sun Jun 07 02:30:31 +0000 2009 - @stolzedesigns I figured out that I had accidently altered the screen brightness by hitting some keys. Thanks. Sat Jun 06 02:48:19 +0000 2009 - something is wrong with my laptop screen. and the fn buttons is not working! Fri Jun 05 17:50:08 +0000 2009 - I haven't posted a blog article for so long. I wonder why is that? Thu Jun 04 21:44:29 +0000 2009 - why isn't the items passing on to paypal? Thu Jun 04 19:46:42 +0000 2009 - is working on PayPal Express Checkout API for a custom checkout process. Thu Jun 04 07:56:28 +0000 2009 - PHP DOMDocument really makes API integration much easier. Thu Jun 04 07:02:01 +0000 2009 - Just finished a php class object using the Flickr API. Wed Jun 03 23:14:11 +0000 2009 - might have a new client referred from an existing happy client Wed Jun 03 16:57:07 +0000 2009 - are you skynet wolfram? http://bit.ly/g8DsI Wed Jun 03 16:52:08 +0000 2009 - good morning tweeters! getting ready for an exciting day today! Wed Jun 03 06:33:33 +0000 2009 - About to start on Flickr integration into the LCLA website. Wed Jun 03 06:31:53 +0000 2009 - 10 types of freelancers http://bit.ly/lFFaU Tue Jun 02 17:06:38 +0000 2009 - enjoying a bowl of noodles while coding out an ecommerce website. Tue Jun 02 08:54:57 +0000 2009 - Meeting with LCLA owner tomorrow. Big day tomorrow.


[...] ynou create a website for one client, and another website for another client. Both of them wants to integrate a Twitter feed into their website. While creating the functions for one website, you are most likely to copy and [...]
Hello i am so delighted I found your blog, I really found you by mistake, while I was searching Yahoo for something else, Anyway I am here now and would just like to say thanks for a tremendous blog posting and a all round interesting blog (I also love the theme/design), I do not have time to read it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read more,
No joke you know what you are talking about , thank you
Hey thanks for this post ! You have made my day! I will bookmark you
I loved every single word of this post !
Well I ve seldom readed something engaging like this one ! Please, write more and let me know!