Using the Twitter API
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

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.
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?
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.
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?
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.
[...] Using the Twitter API | Ashley Ford – PaperMashup.com Good read about using the Twitter API! (tags: twitter api) [...]
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.
where do you recommend copying and pasting the regular expression code?
should it be inside the foreach { } or should it be before or after?
never mind…figured it out.
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
[...] Using the Twitter API This is an excellent introduction to using the Twitter API. The API offers many different ways to connect to your details including XML, JSON, Atom and RSS. This tutorial uses XML, PHP and cURL. [...]
[...] Usando la API de Twitter [...]
[...] Using the Twitter API This is an excellent introduction to using the Twitter API. The API offers many different ways to connect to your details including XML, JSON, Atom and RSS. This tutorial uses XML, PHP and cURL. [...]
[...] Using the Twitter API This is an excellent introduction to using the Twitter API. The API offers many different ways to connect to your details including XML, JSON, Atom and RSS. This tutorial uses XML, PHP and cURL. [...]
[...] Here’s how to use PHP CURL and the TinyURL api to generate tiny urls on the fly. This is a similar tutorial to the one I wrote a while back on using the Twitter API [...]
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…
Nevermind, the download code works great. Probably should just update the code snippet in the page. Thanks again!
Hey Richard,
Thanks for the comment, glad you found it useful, i’ve updated the code snippet, thanks for letting me know
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.
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?
@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
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’m glad you found the script useful i can see you used it on twiogle.com
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!
[...] modifica è piuttosto semplice e prevede l’uso di preg_match(); — ci viene in aiuto un intervento di Ashley Ford, che modificheremo perché si adatti alle nostre esigenze. Occorre riprendere lo [...]
as it do for show “direct messages” and time stamp
@Fabrix, not quite sure what your talking about
could you explain?
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”
for show date:
$data1 = date("F j, Y G:i",strtotime($twit1->created_at));.
…
echo "".$data1." from ", $twit1->source,"";}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.
by that does not function with: ” http://twitter.com/direct_messages.xml ”
anybody has the solution
@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
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:)
@simon thanks for the comment and glad to hear you found it useful. All the best
“foreach ($tweeters->direct_message as $twit1) {”
……………………………………………………………………….
thanks!
but not show image avatar!
has the solution?
How do I just make it display 3 tweets
@dwayne i think you can now add &limit=3 but i haven’t tested it
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!
@david you might be best looking at this tutorial which uses the twitter search API http://papermashup.com/using-the-twitter-search-api/
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.
@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.
[...] 2. Using the Twitter API [...]
when i change the settings and upload the page to my website, i get a blanco page. how it that possible?
[...] Using the Twitter API [...]
Thanks for this timely tutorial, just what I needed.
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
such a great simple script. i love it.
Would love to see similar thing working with Direct Messages, #searches, and searches without #. All with reply option.
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?
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
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
@Ryan, thanks for the tip i’ll make an update to the post with the new code. thanks again!
Ashley,
Tested and ran the script. Everything ok!
Very good!
Thanks!
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!
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
[...] This post was Twitted by JayNeff [...]
@Sanae check out this jQuery ajax example http://papermashup.com/jquery-php-mysql-username-availability-checker/ it works on the same principle as what you would need. Let me know if it helps. I may write a post on twitter / ajax in the future.
Happy New Year!
Happy new year to you too Ashley, and thank you for the tip i will try it out this weekend.
Leave a comment...
Connect
Latest Poll
Recent Posts