Twitter Feed Reader Using PHP

Here’s a simple PHP snippet that I’m sure some of you might find pretty handy: it’s a Twitter feed reader! Copy the code below and simply replace all the necessary info with the proper Twitter user handle, run it, and then let it do its magic. The reader takes a username, load the user’s feed, and display it on a page.

Twitter.php

<?php 
class Twitter{ 
 protected $twitURL = 'http://api.twitter.com/1/'; 
 protected $xml; 
 protected $tweets  = array(), $twitterArr = array(); 
 protected $pversion = "1.0.0"; 
 public function pversion(){ 
 return $this->pversion; 
 } 
 public function loadTimeline($user, $max = 20){ 
 $this->twitURL .= 'statuses/user_timeline.xml?screen_name='.$user.'&count='.$max; 
 $ch        = curl_init(); 
 curl_setopt($ch, CURLOPT_URL, $this->twitURL); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
 $this->xml = curl_exec($ch); 
 return $this; 
 } 
 public function getTweets(){ 
 $this->twitterArr = $this->getTimelineArray(); 
 $tweets = array(); 
 foreach($this->twitterArr->status as $status){ 
 $tweets[$status->created_at->__toString()] = $status->text->__toString(); 
 } 
 return $tweets; 
 } 
 public function getTimelineArray(){ 
 return simplexml_load_string($this->xml); 
 } 
 public function formatTweet($tweet){ 
 $tweet = preg_replace("/(http(.+?))( |$)/","<a href=\"$0\">$1</a>$3", $tweet); 
 $tweet = preg_replace("/#(.+?)(\h|\W|$)/", "<a href=\"https://twitter.com/i/#!/search/?q=%23$1&src=hash\">#$1</a>$2", $tweet); 
 $tweet = preg_replace("/@(.+?)(\h|\W|$)/", "<a href=\"http://twitter.com/#!/$1\">@$1</a>$2", $tweet); 
 return $tweet; 
 } 
}     

example.php

<?php 
$twitter = new Twitter(); 
$feed = $twitter->loadTimeline("phpsnips")->getTweets(); 
foreach($feed as $time => $message){ 
 echo "<div class='tweet'>".$twitter->formatTweet($message)."<br />At: ".$time."</div>"; 
}

Incoming search terms for the article:

Related Posts

How to Create a Geometric Shaped Typography with Grungy Background

Optimize Your Site For Retina Display

How to Create a Clean and Colorful Web Layout

Create An Instagram Widget In Photoshop

1 Comment

  1. Jenna

    05.06.2013

    Thanks for finally writing about >Twitter Feed Reader Using PHP
    | Blogfreakz - Web Design and Web Development resources
    <Liked it!