The code below no longer works as-is with the Twitter API update to 1.1 as of 2013-06-11. The 1.1 API requires oAuth which requires a server side component. Here’s a PHP way to interact with the new API. Googling around will find you many other libraries and such. There is an all-JavaScript method for getting tweets, but it may be a bit of a loophole that you may not want to count on.
<?php
function getTwitterStatus($userid){
$url = "https://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=1&include_rts=1callback=?";
$xml = simplexml_load_file($url) or die("could not connect");
foreach($xml->status as $status){
$text = $status->text;
}
echo $text;
}
// USAGE
getTwitterStatus("chriscoyier");
?>
All I get is a ‘Could not Connect’ Error. Code doesn’t seem work.
The code works. There are a couple reasons you might get a “Could no Connect” that come to mind:
1. Your installation of PHP does not support simple_xml
2. Your server is not able to connect to an external site.
The first scenario is probably more likely.
can only receive the latter can not appear more
Another reason for the code to not work properly is that the twitter account used to retrieve the status update may be ‘locked’ (private accounts).
You should set it up to public status update ;)
Thanks for this snippets works perfect for me!
I would advise against using the XML format, at least for now. It appears that retweets are not included in the XML and JSON feeds. That wouldn’t be so bad, except that it doesn’t just skip a retweet – it returns a blank tweet!
To get around this I use the RSS format. That comes with its own unique challenges and a different XML structure but at least it returns those retweets.
More info:
http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline
How would you change it to show the last X tweets instead of just 1?
in
$url
instead of 1 incount
use ‘x’ where ‘x’ defines the number of tweets.I implemented the above code but the links in my tweets are not active even though they are active on my twitter page. Have any thoughts?
I know you nearly lost your shit trying to publish this code, but it says everything you need to know in the remember section right by this comment form.
Thanks for the code, works perfect!
i used code it works for me but i cannot get the date of tweets. Can you help me to get the tweet date.
Don’t work this code :( ..
Not sure if this has been posted, I found a slight error with your foreach loop.
if you set the ?count=5 (or something other than one) you will only echo the 5th most recent tweet you’ve made. If that is what you’re after, great, but if you want to show the 5 most recent tweets, you’ll need to put the “echo $text;” within the foreach:
in the $url, change ?count=1 to ?count=5 or something other than one
Well, it worked perfectly at first, then after refreshing the page, it gave a could not connect to server error. Wonder why it worked initially?
awesome, thank you Chris.
Both versions works great for me, now to just stylize it and put it on my homepage for my users. Thanks!
i got it every thing just working fine :) thx Chris
It works intermittently for me. It will be displaying everything fine and then, a moment later, it stops and I get the “Could not Connect” error.
Any ideas?
I was having issues getting it to work and I realized that
$text = $status->text;
would need to be
$text .= $status->text;
Otherwise the code will only print one.
Good tricks!
I made some modifications to the script. Hope this help someone! :) `
Couldn’t get this to work in mine. I used this url and it worked:
$url = “http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=$userid&count=1”;
i used @Walter code it works for me but i cannot get the date of tweets. Can anyone help me to get the tweet date.
I’m working with a Drupal install, trying to forego using OAuth and the current iteration of the Twitter module, using this code instead. Unfortunately the “Could not connect” error is site crippling for me. It gives me a white screen and completely locks me out of accessing my site, until the error finally just (randomly) ceases and the code is functional again. Is there any way to stop this behavior, or a bit of code that might work “better” for my needs? Any help is appreciated. Thanks!
I changed a little something in Walter’s code because Greek characters showed up like questionmarks for me.
So I replaced utf8_decode($text) with html_entity_decode($text) and now my Greek chars are just fine!
<?php
function getLastXTwitterStatus($userid,$x){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=$x";
$xml = simplexml_load_file($url) or die('could not connect');
echo '<ul>';
foreach($xml->status as $status){
$text = twitterify( $status->text );
echo '<li>'.utf8_decode($text).'</li>';
}
echo '</ul>';
}
function twitterify($ret) {
$ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" >\\2</a>", $ret);
$ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" >\\2</a>", $ret);
$ret = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" >@\\1</a>", $ret);
$ret = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" >#\\1</a>", $ret);
return $ret;
}
//my user id kenrick1991
getLastXTwitterStatus('kenrick1991',5);
?>
I have been checking out different way’s to embed twitter in php and this is by far the best and easiest I’ve seen.
Is there a way to embed hashtag’s like through twitter search instead of a user id? Would be great for events!
How do I cache my tweet because my page seem to load slower than normal?
Does anybody know how I can use PHP to grab the StatusesCount from a Twitter account and then return to it to a webpage as a plain text number to format with CSS? I am currently displaying the 5 most recent tweets and below have a link ‘view more tweets’ that links to the twitter account but I am keen to say ‘view more tweets, we have x available to read’. Where x is the count that gets returned through the PHP. Can anybody help, I thought it would be easy to find, but having searched for the past two hours I haven’t been able to track down how to do it. Thanks T
Great thread! I went with the @walter code for a recent theme build and to switch out the $userid with a name input by the theme user I just added a variable at the top and replaced the username in the function call at the bottom:
Nice for a WordPress theme build.
Is there a way to use Walter’s code but exclude any @replies?
Is there ANY way to display multiple tweets, but only one at a time? Or even put them all in a singular line with something like a bunch of hyphens separating them? I’m trying to create a scrolling ticker..
I actually figured it out! PHP is cool.
Just Click on this Link
https://twitter.com/statuses/user_timeline/ranasaani.json
You will get the Json object
@usman this is the simplest way I have seen thanks..
I am retrieving latest tweet with count=1.
But when i delete the latest tweet, twitter returns blank. I am using XML/JSON format.
thanks a lot for simple and great script :)
I found a class here on this site http://www.thetutlage.com/post=TUT177
Seems promising to me..
How do you make any links in the tweet hyperlinked?
I got it to work, but the link is text not a link.
thanks
It was working until yesterday, but today when i checked, its giving could not connect message for my website http://ankurgupta.com/ and coz of this error the full page is also not loading :(
If the last tweet of the user is a “retweet” you will get zero results, an empty array. Or if the count is set to 3 and latest 3 tweets of the user are all retweets, you will get an empty array again as a result, the same scenario.
To achieve this, you need to use the newer version of the API and the parameter include_rts=true, with count=1. So your link should look like this:
https://api.twitter.com/1/statuses/user_timeline/$userid.xml?count=1&include_rts=1
Here is my very up to date latest tweet (even if it is a retweet):
https://api.twitter.com/1/statuses/user_timeline/f000k.xml?count=1&include_rts=1
BTW, why don’t you use JSON instead of XML?
awesome! worked for me.. thx a lot… God bless you.
Hi! 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. Anyhow, I’m definitely delighted I found it and I’ll be book-marking and checking back often!
It absolutely works, but a “linkify” option for the status would’ve suited more people I suppose.
Anyways, like one of the Johns above said, this is the easiest solution that I know of. Thanks!
Michael Shur, that intermittently “could not connect” issue is a Twitter one rather than a script problem. The worst case scenario where you don’t blame Twitter or the script is a setting on your server, but I doubt it.
Thanks a lot for the function. How can I overcome the “Rate limit exceeded. Clients may not make more than 150 requests per hour.” I see that using OAuth is one of the solutions, but not sure exactly how to implement it. Any help would be great.
Thanks.
What I did was cache the last tweet in a file, that way if you hit the rate limit error or for any reason cannot get the latest tweet from twitter, it will use the local cache. This prevents errors on your site. You can find it here
Works for me and simple to use too, Ive tried about 3 different widgets in the last hour that did not meet my requirements. Was starting to drive me mad… Thanks :)
Great code works perfectly for me!
Well.. except for one thing
Is there any way to just display normal tweets rather than direct messages/mentions/replies?
FIX:
$userid = htmlspecialchars($userid);
$url = ‘url?’ . $userid . ‘url’;
This script is just what I was looking for!
It worked for me, thank’s
I am working on a website for a client and he wants his entire tweet to link to the individual tweet on twitter. I’ve wrapped the ul in an a tag, which works fine, but I am not sure what php I need to put in the href attribute to make it link to the individual tweet.
Could any of you help me out?
Thanks in advance!
Just wanted to say thanks for the code! Works perfectly.
Perfect! Quick, simple and does the job. CSS Tricks strikes again!
Hi! Stopped working yesterday!! Any changes in the twitter API? Thanks.
Twitter discontinued with XML, need fix to work with JSON and API 1.1
“Twitter discontinued with XML, need fix to work with JSON and API 1.”
Yes, a fix or substitute would be extremely useful please. Anyone?
It would be great for someone to explain a way to get Twitter posts in plain text format rather than having to use the Twitter widget.
Hi Dan
Im not sure if this post will allow outbound links but i’ve written made a fix available on my site here
http://www.naileditdesign.com/tutorials/twitter-feed-for-api-v1-1
Just thought I’d share I wrote a piece on twitter embedded timelines using API v1.1 OAuth.
Take it easy guys.
Thanks to the above 2 posts for their updates, both are appreciated!
After twitter api 1.1 no allowed for basic auth
Try to check https://dev.twitter.com/docs/api/1.1
How to control the number of tweet
For this you need to work closely with roofing Melbourne experts to ensure
that you have also considered the weight and working load your roof will be able to bear.
(3) It is also useful if you have pets, would keep
lights around the barn unwelcome visitors. To add insult to injury, the roofing contractor
that would put his workers up on your roof without insurance is the same contractor that would probably ignore most safety requirements.
<?php $ret = preg_replace("/#(\w+)/", "#\\1“, $ret); ?>
<?php $ret = preg_replace("/#(\w+)/", "#\\1“, $ret); ?>
Thanks Walter
in place of first line use second line
above two comments are due to without php
everything change: https://dev.twitter.com/rest/reference/get/statuses/user_timeline
new twitter docs to api get->status->usertimeline