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.
$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
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!
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.
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 )
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
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!?!
Does anyone have a solution for converting this to oAuth yet?
please we are waiting for the upgrade
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.
Hi.
This twitter rss demo not working. And your twitter demo not working.
This information not for Business, also not to look for Money,but to share Phenomenon to us all.
Hello Sir,
Great tutorial to the Twitter API.
Thanks!
Great work. Simple and useful!
anybody has the solution
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.
Oh, I see if i use
echo $twi;
I see all the Asian Signs, but with $twit1->user->name it doesnt work, an ideas?
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
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
Pingback: Twitted by JayNeff
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!
Ashley,
Tested and ran the script. Everything ok!
Very good!
Thanks!
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
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
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?
Would love to see similar thing working with Direct Messages, #searches, and searches without #. All with reply option.
such a great simple script. i love it.
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
Thanks for this timely tutorial, just what I needed.
Pingback: Andivista Info und Technikblog » Blog Archive » Twitter API
when i change the settings and upload the page to my website, i get a blanco page. how it that possible?
Pingback: 10 Twitter API Tutorials. « The Domage
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.
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!
How do I just make it display 3 tweets
“foreach ($tweeters->direct_message as $twit1) {”
……………………………………………………………………….
thanks!
but not show image avatar!
has the solution?
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:)
by that does not function with: ” http://twitter.com/direct_messages.xml ”
anybody has the solution
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.
for show date:
$data1 = date("F j, Y G:i",strtotime($twit1->created_at));
.
…
echo "".$data1." from ", $twit1->source,"";}
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”
as it do for show “direct messages” and time stamp
Pingback: Mostrare lo status di Twitter su WordPress, senza plugin / 2 ↠brand:GNU · Italians Do It Better
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!
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.
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?
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.
Nevermind, the download code works great. Probably should just update the code snippet in the page. Thanks again!
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…
Pingback: PHP CURL & Tiny URL | Papermashup.com
Pingback: 50 Twitter Tools and Tutorials For Designers and Developers | The Scripts Zone
Pingback: 50 Công cụ Twitter hay dà nh cho Designers và Developers | Giải Pháp Số
never mind…figured it out.
where do you recommend copying and pasting the regular expression code?
should it be inside the foreach { } or should it be before or after?
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
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?
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.
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?
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?
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?
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.
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.
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.
Designer and web developer, Co-founder and Technical Director at Harkable.com London. Previously I worked at InMobi, Spotify and MySpace. Interests include photography and making short videos. Also an avid F1 fan. I also run Mega Infographics for your daily dose of the best infographics.
Follow us on Twitter and get in-stream updates.
Subscribe to all the Papermashup tutorials and articles straight to your RSS reader.
Sign up and get all the Papermashup tutorials straight to your inbox.
77 discussions around Using the Twitter API