Twitter Status With PHP and Twitter JSON (snippet)

WARNING: The below code is deprecated as of June 11, 2013. I’ve created a snippet that’s updated here: Twitter Feed With PHP and JSON using API v1.1

Note: the API has a limit of 150 pings per hour, so be careful out there. I’ll have a snippet soon on caching tweets.

$userid = 'johnbhartley'; //your handle
$count = '5';
$responseJson = file_get_contents(''.$userid.'&include_rts=1&count='.$count);

if ($responseJson) {
  $response = json_decode($responseJson);

echo '<ul>';
foreach ($response as $tweet) {
    $tweet_text = $tweet-&gt;text; //get the tweet
    // make links link to URL
    $tweet_text = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1&lt;a href='\2'&gt;\2&lt;/a&gt;", $tweet_text); 
    // make hashtags link to a search for that hashtag
    $tweet_text = preg_replace("/#([a-z_0-9]+)/i", "&lt;a href="$1"&gt;$0&lt;/a&gt;", $tweet_text);
    // make mention link to actual twitter page of that person
    $tweet_text = preg_replace("/@([a-z_0-9]+)/i", "&lt;a href="$1"&gt;$0&lt;/a&gt;", $tweet_text);
    // display each tweet in a list item
    echo "&lt;li&gt;" . $tweet_text . "&lt;/li&gt;n";
echo '</ul>';

This snippet will help you add your twitter status to any site with PHP and the Twitter JSON file. It is output into a list and the number of tweets is controlled by the variable $count. Be sure to switch out my name for your twitter handle, unless you want to show all of my tweets, which would be weird.

This is just a quick fix to what I had previously used, which was the XML file, which as of yesterday, no longer seemed to work. Happy status-showing and as always, let me know if you’ve found a better way to pull this off.

Note: More explanation to come laters.

Notify of
Newest Most Voted
Inline Feedbacks
View all comments
8 years ago

And I was wondering what had happened with fetching twitter statuses to my website! Thanks for this post, it’s solved my task.

Twitter has become a little bit annoying with their policy changes (as of August 2012) and this quiet deprecation of XML format…

Sacha 'Vaati' Veyrier
8 years ago

Thanks a lot, I went through a lot of snippets , none were working ; but this one works just fine. Thanks again 🙂

John Hartley is a Director of Product Engineering at Beam Dental in Columbus, OH. With 5+ years of leadership experience he has worked in startups, agencies, and began his career as a freelance Front End Developer. Always looking to iterate, this blog is a place for him to share his knowledge as well as hone his craft, challenge assumptions, and build a strong base of leadership and management knowledge. Connect with him on LinkedIn

Would love your thoughts, please comment.x