Papermashup

Subscribe


Tweets


"RT @kycutwilson: @ashleyford @burgerbeartom incredible. There's 5 more left! Shout about it!!"

@ashleyford 24 hours ago

"@burgerbeartom @kycutwilson finally got around to using my free burgers for life! And we weren't disappointed. http://t.co/nJ6p2nLtg4"

@ashleyford 1 week ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Using the Twitter API

AshleyAshley

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

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 80
  • Cheri
    Posted on

    Cheri Cheri

    Reply Author

    HELP… so some strange reason my Twitter Feed use to work and now it doesn’t. I create my websites using Adobe Muse (I am a designer not a developer) and a buddy of mine sent me code that worked awesome and I tweaked it a wee bit to get the font colour and leading I wanted.

    Can someone have alook at my site (looking at the source file) and tell me what the heck has happened? I would love it if someone can find the problem and email me the changes or suggestions.

    Thanks
    Cheri


  • Lucinda
    Posted on

    Lucinda Lucinda

    Reply Author

    Hey I know this is off topic but I was wondering
    if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.

    I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.


  • Christie
    Posted on

    Christie Christie

    Reply Author

    Howdy! I could have sworn I’ve been to this site before but after checking through some of the post I realized it’s new to
    me. Anyways, I’m definitely happy I found it and I’ll be bookmarking and checking back
    often!


  • Proxy Twitter – Private Fast Proxiy, specifically deisgned for Twitter software, Turbocharge Twitter Promotion!

    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!


  • TwitterProxies.com | Private Proxies specifically deisgned for Twitter software! Turbocharge Twitter Promotion!

    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.


  • Shah Alom
    Posted on

    Shah Alom Shah Alom

    Reply Author

    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 )


  • Bugz R
    Posted on

    Bugz R Bugz R

    Reply Author

    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


  • Tweets Junkie
    Posted on

    Tweets Junkie Tweets Junkie

    Reply Author

    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!?!


  • Lorraine
    Posted on

    Lorraine Lorraine

    Reply Author

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


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

    please we are waiting for the upgrade


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

    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.


  • Cosmos
    Posted on

    Cosmos Cosmos

    Reply Author

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


  • Teacher
    Posted on

    Teacher Teacher

    Reply Author

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


  • hardeep
    Posted on

    hardeep hardeep

    Reply Author

    Hello Sir,

    Great tutorial to the Twitter API.
    Thanks!


  • odalcet
    Posted on

    odalcet odalcet

    Reply Author

    Great work. Simple and useful!


  • hermes kelly bag
    Posted on

    hermes kelly bag hermes kelly bag

    Reply Author

    anybody has the solution


  • Prasenjit Barman
    Posted on

    Prasenjit Barman Prasenjit Barman

    Reply Author

    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.


  • Human
    Posted on

    Human Human

    Reply Author

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


  • Human
    Posted on

    Human Human

    Reply Author

    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


  • Shuman
    Posted on

    Shuman Shuman

    Reply Author

    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:xampphtdocstwittertwitter-api.php on line 48. Could you tell me where is the problem?

    Thanks
    Shuman


  • Sanae Belkhir
    Posted on

    Sanae Belkhir Sanae Belkhir

    Reply Author

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


  • Sanae Belkhir
    Posted on

    Sanae Belkhir Sanae Belkhir

    Reply Author

    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


  • Matt
    Posted on

    Matt Matt

    Reply Author

    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!


  • Fabio Aires
    Posted on

    Fabio Aires Fabio Aires

    Reply Author

    Ashley,

    Tested and ran the script. Everything ok!

    Very good!

    Thanks!


  • Ryan Barr
    Posted on

    Ryan Barr Ryan Barr

    Reply Author

    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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Ryan, thanks for the tip i’ll make an update to the post with the new code. thanks again! 😉


  • Ryan Barr
    Posted on

    Ryan Barr Ryan Barr

    Reply Author

    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


  • Mark
    Posted on

    Mark Mark

    Reply Author

    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?


  • Dominic
    Posted on

    Dominic Dominic

    Reply Author

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


  • ravi
    Posted on

    ravi ravi

    Reply Author

    such a great simple script. i love it.


  • Anthony
    Posted on

    Anthony Anthony

    Reply Author

    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


  • Diane Stafford
    Posted on

    Diane Stafford Diane Stafford

    Reply Author

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


  • Bram
    Posted on

    Bram Bram

    Reply Author

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


  • Richelle
    Posted on

    Richelle Richelle

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @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.


  • David Nahmias
    Posted on

    David Nahmias David Nahmias

    Reply Author

    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!


  • Dwayne Paisley-Marshall
    Posted on

    Dwayne Paisley-Marshall Dwayne Paisley-Marshall

    Reply Author

    How do I just make it display 3 tweets


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @dwayne i think you can now add &limit=3 but i haven’t tested it


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

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

    but not show image avatar!

    has the solution?


  • Simon
    Posted on

    Simon Simon

    Reply Author

    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:)


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @simon thanks for the comment and glad to hear you found it useful. All the best


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

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

    anybody has the solution


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @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 :)


  • aaron
    Posted on

    aaron aaron

    Reply Author

    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.


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

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

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


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

    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”


  • Fabrix
    Posted on

    Fabrix Fabrix

    Reply Author

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      @Fabrix, not quite sure what your talking about :( could you explain?


  • Andi
    Posted on

    Andi Andi

    Reply Author

    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!


  • Twitter Search
    Posted on

    Twitter Search Twitter Search

    Reply Author

    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.


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      I’m glad you found the script useful i can see you used it on twiogle.com


  • oni
    Posted on

    oni oni

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      @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


  • nick
    Posted on

    nick nick

    Reply Author

    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.


  • Richard
    Posted on

    Richard Richard

    Reply Author

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


    • Ashley
      Posted on

      Ashley Ashley

      Reply Author

      Hey Richard,

      Thanks for the comment, glad you found it useful, i’ve updated the code snippet, thanks for letting me know 😉


  • Richard
    Posted on

    Richard Richard

    Reply Author

    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…


  • TV On Twitter
    Posted on

    TV On Twitter TV On Twitter

    Reply Author

    never mind…figured it out.


  • TV On Twitter
    Posted on

    TV On Twitter TV On Twitter

    Reply Author

    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
      Posted on

      Ashley Ashley

      Reply Author

      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


  • TV On Twitter
    Posted on

    TV On Twitter TV On Twitter

    Reply Author

    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?


  • Derek P. Collins
    Posted on

    Derek P. Collins Derek P. Collins

    Reply Author

    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?


  • Derek P. Collins
    Posted on

    Derek P. Collins Derek P. Collins

    Reply Author

    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?


  • Markus
    Posted on

    Markus Markus

    Reply Author

    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?


  • Ashley
    Posted on

    Ashley Ashley

    Reply Author

    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.


  • Ashley
    Posted on

    Ashley Ashley

    Reply Author

    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.


  • Ashley
    Posted on

    Ashley Ashley

    Reply Author

    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.


  • Ashley
    Posted on

    Ashley Ashley

    Reply Author

    Hey, yeah you can easily turn the links into tags using php regular expression, i have a post on this here: http://papermashup.com/php-regular-expression-twitter-links/ let me know if you have any problems adding it.