Use your left/right keys to browse tutorials
Using the Twitter API

Using the Twitter API

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on January 22, 2009

TWITTER HAS CHANGED ITS API METHOD THIS TUTORIAL WILL NO LONGER WORK.

Here’s a simple introduction on using the Twitter API. The API offers many different ways to connect to your details including xml, json, atom, and rss. Im going to use xml, php and curl to read an xml file to get my latest followers tweets and display them in the format below.

This method of parsing the xml file requires PHP5 and uses the SimpleXMLElement class.

The Code


$login = "username:password";

$tweets = "http://twitter.com/statuses/friends_timeline.xml?count=5";

$tw = curl_init();

curl_setopt($tw, CURLOPT_URL, $tweets);

curl_setopt($tw, CURLOPT_USERPWD, $login);

curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);

$twi = curl_exec($tw);

$tweeters = new SimpleXMLElement($twi);

$latesttweets = count($tweeters);

if ($latesttweets>2) {

	echo "<h3>".$latesttweets." latest tweets from the users I follow | <a href=\"http://www.twitter.com/ashleyford\">Follow Me!</a></h3>";

	}

## Printing/Dumping the data

foreach ($tweeters->status as $twit1) {

$description = $twit1->text;

      $description = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", $description);
$description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", "'\\1<a href=\"\\2\" >\\2</a>'", $description);
$description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r<]*)#ise", "'\\1<a href=\"http://\\2\" >\\2</a>'", $description);

echo "<div class='user'><a href=\"http://www.twitter.com/", $twit1->user->screen_name,"\" target=\"_blank\"><img border=\"0\" class=\"twitter_followers\" src=\"", $twit1->user->profile_image_url, "\" title=\"", $twit1->name, "\" /></a>\n";
echo "<div class='name'>", $twit1->user->name,"</div>";
echo "<div class='followers'>", $twit1->user->location,"</div>";
echo "<div class='location'>", $twit1->user->url,"</div>";
echo "<div class='text'>".$description."<div class='description'>From ", $twit1->source,"</div></div></div>";}

curl_close($tw);

The first thing you need to do to connect to the API is to add your login details in the variable $login, this is required to authenticate the connection to the API. Next we specify which xml file we want to get data from in our case we’re targeting the friends_timeline: http://twitter.com/statuses/friends_timeline.xml?count=5 at the end i’ve appended a parameter that limits the number of results to 5, you can change this to anything up to 20.

Then using curl we can authenticate the connection and parse the xml file using the SimpleXMLElement class in PHP5. Then we cycle through the results in a ‘foreach’ loop and display the results on the page. you can then style it with CSS.

UPDATE:

To enable @reply links and tiny url links in your updates i have added regular expression, the new code is above, i have also updated the demo

you can change the xml file, to target different user data, you may have to tweek the code to point to the correct xml tags. Here is a list of xml files to play with.

Twitter Public Timeline.

http://twitter.com/statuses/public_timeline.xml

Users Timeline.

http://twitter.com/statuses/user_timeline.xml

Shows a users @replies

http://twitter.com/statuses/replies.xml

Shows a users friends list up to 100 (with most recent tweet)

http://twitter.com/statuses/followers.xml

demodownload



Recent shares

More tutorials from Papermashup
Comments
77 discussions around Using the Twitter API
  1. I used to be suggested this web site by way of my cousin. I’m no longer sure whether this submit is written by way of him as nobody else realize such precise approximately my problem. You are wonderful! Thanks!

  2. I do consider all of the concepts you’ve presented for your post. They are really convincing and will certainly work. Nonetheless, the posts are too quick for novices. Could you please prolong them a little from subsequent time? Thank you for the post.

  3. Shah Alom says:

    Hi there,
    I think twitter do not support the simple authentication using curl You have used in this article. Because when i used your code with just a print_r($tweeters) function, it show me the below result #

    SimpleXMLElement Object ( [error] => Basic authentication is not supported )

  4. Bugz R says:

    Does anyone have the updated version of this code????? if yeah cud u please post it here i really need it for my final year assignment!!!! cherrzzzzzzzzzzz

  5. Tweets Junkie says:

    Could someone please help me update this code so that it is compatible with the new OAuth using a Single Access Token? I’m not a programmer, but I’m thinking the conversion is probably not too complicated. I’ve been using this code, and now my little site that brings in tweets has been down for a month. Help!?!

  6. Lorraine says:

    Does anyone have a solution for converting this to oAuth yet?

  7. Fabrix says:

    please we are waiting for the upgrade

  8. Fabrix says:

    August 31, 2010 Basic Auth has been deprecated. All applications must now use OAuth.

    Don’t fret! @twitterapi is here to help! Feel free to reach out to us directly, or via our Twitter Development Talk group.

    The switch to OAuth is a good thing! You, as the application developer,

    * don’t have the burden of keeping potentially damaging credentials for your users (especially considering that a lot of people use the same password for multiple services);
    * don’t have to worry about the user changing their password — a user can change his or her password and the OAuth “connection” to your app will still work;
    * don’t have to worry about other applications masquerading as your application as only your application can set the byline with your application name;
    * will eventually have access to more trusted APIs from Twitter that will only be available to “trusted” OAuth-enabled applications; and
    * will be contributing to the web of trust between users, service providers, and applications.

  9. Cosmos says:

    Hi.
    This twitter rss demo not working. And your twitter demo not working.

  10. Teacher says:

    This information not for Business, also not to look for Money,but to share Phenomenon to us all.

  11. hardeep says:

    Hello Sir,

    Great tutorial to the Twitter API.
    Thanks!

  12. odalcet says:

    Great work. Simple and useful!

  13. anybody has the solution

  14. Can any body provide me a php code/script package, so that i can apply it to my website and login in tweeter.com from my site.

  15. Human says:

    Oh, I see if i use
    echo $twi;
    I see all the Asian Signs, but with $twit1->user->name it doesnt work, an ideas?

  16. Human says:

    Hi Shuman,
    you need to edit the php.ini file in XAMMPP und then you need to remove the semikolon (;) from this line “;extension=php_curl.dll”. After an XAMPP restart it works.

    @Ashley It works great for me, but i request tweets with Japanese Signs. The Problem is, i get stuff like “­ãƒ¼ï¼Ÿï¼ 誔.
    I tried teh JSON Methode at their is the same problem.
    Can You help me ?

    (This account http://twitter.com/ayu_19980408)

    thx

  17. Shuman says:

    Hello Ashley,

    At first thanks to you for a great script. When I run this script in my current host, this script works properly and correctly displayed 5 twittets. But when I run this script in my localhost this gives me the following error message: Call to undefined function curl_init() in C:\xampp\htdocs\twitter\twitter-api.php on line 48. Could you tell me where is the problem?

    Thanks
    Shuman

  18. Happy new year to you too Ashley, and thank you for the tip i will try it out this weekend.

  19. Pingback: Twitted by JayNeff

  20. great post, any ideas how to implement AJAX so that the results will be real time..?
    any help would be much appreciated

    Happy new year

  21. Matt says:

    Hi Ashley, thanks for this tutorial.
    Every examples are working (@replies, timeline,..) except the followers listing, it gives me an empty list, no error…
    Any idea why?
    I can’t figure out myself.
    Thanks!

  22. Fabio Aires says:

    Ashley,

    Tested and ran the script. Everything ok!

    Very good!

    Thanks!

  23. Ryan Barr says:

    Ashley,

    My comment before is incorrect. Sorry. I missed a part, it is actually the following:

    $description = preg_replace(“#(^|[\n ]|\W)@([a-zA-Z0-9_-]+)(^\W)#ise”, “‘\\1@\\2‘”, $description);

    Best,
    Ryan Barr

  24. Ryan Barr says:

    Hey Ashley,

    Not a bad start for your tutorial. After building a more complex one myself, I did some searches on Google to see how I compared. For your @reply links, if there are trailing or preceding characters (such as .@username or @username,) the link breaks. The following RegEx should take care of that:

    $description = preg_replace(“#(^|[\n ]|\W)@([a-zA-Z0-9_-]+)#ise”, “‘\\1@\\2‘”, $description);

    Again, great job. Maybe we can work on a script together someday.

    Best,
    Ryan Barr

  25. Mark says:

    1) if I try this one:
    $login = “my_user_name:*******”;

    $tweets = “http://twitter.com/statuses/friends/my_user_name.xml”;

    $tw = curl_init();

    2) I only get:
    26 latest tweets from the users I follow | Follow Me!

    The number 26 is right! :)
    But I don’t see anything :(

    Anyone?

  26. Dominic says:

    Would love to see similar thing working with Direct Messages, #searches, and searches without #. All with reply option.

  27. ravi says:

    such a great simple script. i love it.

  28. Anthony says:

    Thanks for you post. I feel like I’m getting closer to developing my first Twitter app. Just need get familiar with cURL, PHP, and XML.

    Anthony V. Gibby
    Get paid just for using Twitter
    GibbyDevelopments.com
    I’m on Twitter Also

  29. Thanks for this timely tutorial, just what I needed. :-)

  30. Pingback: Andivista Info und Technikblog » Blog Archive » Twitter API

  31. Bram says:

    when i change the settings and upload the page to my website, i get a blanco page. how it that possible?

  32. Pingback: 10 Twitter API Tutorials. « The Domage

  33. Richelle says:

    Ashley, great tutorial! Much appreciation for sharing all of yours.
    Question – how do I exclude the period, comma, or colon at the end of the @name in the description? I get an Error: 404 since the href link has the screen_name. and fails.
    Thanks for the help.

    • Ashley says:

      @Richelle not sure what you mean, are you referring to when you click a link in the description? if that’s right you could use regular expression to strip out and stray characters.

  34. David Nahmias says:

    I like the code, Thank You!

    I need to do a simple search like ‘Basketball’

    how can use your code to do it ?

    Please Help!

    Thank You!

  35. How do I just make it display 3 tweets

  36. Fabrix says:

    “foreach ($tweeters->direct_message as $twit1) {”
    ……………………………………………………………………….
    thanks!

    but not show image avatar!

    has the solution?

  37. Simon says:

    Hi Ashley,

    Thanks a lot for posting this great tutorial. I used your code as a starting point to get twitter posts displayed to my Polycom soundpoint 601. Have tested it in English and Japanese. Very chuffed:)

  38. Fabrix says:

    by that does not function with: ” http://twitter.com/direct_messages.xml

    anybody has the solution

    • Ashley says:

      @fabrix you will need to change this line: foreach ($tweeters->status as $twit1) {

      to:

      foreach ($tweeters->direct_message as $twit1) {

      also to see what data you can pull from the file just check the xml file http://twitter.com/direct_messages.xml (best to use firefox as it removes xml style unlike safari)

      so then to get the date node and echo it you would put: created_at; ?>

      Let me know if you have any problems :)

  39. aaron says:

    Has anyone already written the code to limit the amount of posts that are shown per user?

    Example, I am following 5 people, and only want to show 5 entries. And I do not want one person to suck up more than 2 entries.

    thanks

    nice example….i’m integrated it with some jquery to get the “hot news” snippet on apple.com’s home page.

  40. Fabrix says:

    for show date:
    $data1 = date("F j, Y G:i",strtotime($twit1->created_at));
    .

    echo "".$data1." from ", $twit1->source,"";}

  41. Fabrix says:

    using (http://twitter.com/direct_messages.xml) does not function.
    and
    for show the “date” of the postagem jointly with “source”

    Ex: => “less than 20 seconds ago” from “DestroyTwitter”

  42. Fabrix says:

    as it do for show “direct messages” and time stamp

  43. Pingback: Mostrare lo status di Twitter su WordPress, senza plugin / 2 ← brand:GNU · Italians Do It Better

  44. Andi says:

    Some profile pictures of my followers are too big. I have inserted img border=\”0\” width=\”48\” height=\”48\” class=\”twitter_followers. Thx for the scrpt! Greetings from Berlin!

  45. thats great that you are talking about the twitter api,a good example of searching with the twitter api is on twiogle.com because you can search on twitter and google at the same time.

  46. oni says:

    I get this error when running the script: Fatal error: Cannot instantiate non-existent class: and it refers to this line: $tweeters = new SimpleXMLElement($twi);

    Any ideas on what’s wrong?

    • Ashley says:

      @oni you need to be running PHP5 for this script to work you must be using PHP4 which is why it can’t instantiate the SimpleXML element as it’s only available in PHP5.

      hope that helps

  47. nick says:

    If there is a rt the @username has a : at the end making the link invalid when you click on it. Thought you should know.

  48. Richard says:

    Nevermind, the download code works great. Probably should just update the code snippet in the page. Thanks again!

  49. Richard says:

    Great tutorial. I’m working on getting it onto my website right now. Your regex commands though aren’t escaped in your code sample and I’m getting problems. I’m right now trying to fix it myself but my regex is so out of practice…

  50. Pingback: PHP CURL & Tiny URL | Papermashup.com

  51. Pingback: 50 Twitter Tools and Tutorials For Designers and Developers | The Scripts Zone

  52. Pingback: 50 Công cụ Twitter hay dành cho Designers và Developers | Giải Pháp Số

  53. Pingback: Herramientas y tutoriales de Twitter para diseñadores y desarolladores - diarioTHC, recursos para webmasters, bloggers y diseñadores.

  54. Pingback: 50 Twitter Tools and Tutorials For Designers and Developers | Developer's Toolbox | Smashing Magazine

  55. never mind…figured it out.

  56. where do you recommend copying and pasting the regular expression code?

    should it be inside the foreach { } or should it be before or after?

    • Ashley says:

      Just an update, I’ve amended the code above to include @replies and dynamic links with regular expression in response to ‘TV On Twitter’ the demo and download have also been updated. :) Happy Tweeting

  57. Thanks. Works like a charm! But the only catch is the tinyurl.com links don’t work in the description. is there a way to get those links live?

  58. Pingback: Daily Links | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?

  59. Thanks for that great explanation Ashley.

    FYI: When I moved the Twitter app I was working on from my local server to the production server, I started getting the following error:

    “HTTP/1.1 417 Expectation Failed” and “Expect: 100-continue”

    I did a quick search and found the following solution: http://bit.ly/twitter_error_fix

    Have you ever run into this?

  60. This is a great intro to the Twitter API, thanks!

    I’m not sure if I’m phrasing my question correctly, but do you know if the 3 curl_setopt() options are the only curl options needed? I’ve seen some tutorials that set more options (e.g. CURLOPT_POST, CURLOPT_VERBOSE, CURLOPT_HTTP_VERSION). Are any of the other curl options necessary?

  61. Markus says:

    sorry
    i get always the error message

    SimpleXMLElement Object ( [request] => /statuses/friends_timeline.xml?count=5 [error] => Could not authenticate you. )
    username:password?
    i use %$…. in my password.. is that the reason that curl can´t login?

  62. Ashley says:

    Hey Markus,

    Im guessing that the ‘%$’ in your password could be causing the problem, i’ve never had this problem before, you could try changing your twitter password to see if it works. In the mean time I will have a dig around and see what i can find.

  63. Ashley says:

    Hi Derek,

    Thanks for the comment, the three curl transfer options in the code are the only ones that you need to interact with the twitter api to get data. there’s more documentation here: http://apiwiki.twitter.com/REST-API-Documentation#UserMethods
    I’m writing a tutorial soon on how to post data to twitter which uses CURLOPT_POST to post an update to twitter, CURLOPT_VERBOSE is used for debugging and it returns the headers sent by curl, and CURLOPT_HTTP_VERSION just returns the http server proxy version. You could add the last two options if you wanted to get more information about the curl connection. for example transfer-encoding, when the file was last modified, the server type, and if the connection is open or closed… etc.

    Hope this helps, and let me know if you have any further questions.

  64. Ashley says:

    I’ve never run into this problem before, i will adjust the code with the fix, thanks for bringing this up, it seems that i may need to add the curl header option.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.