-
-
Save cam-gists/3107455 to your computer and use it in GitHub Desktop.
PHP: Codeigniter: Model fetch tweets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
adapted from http://rosstanner.co.uk/2012/01/php-tutorial-twitter-statuses/ | |
*/ | |
class Mytweets extends CI_Model { | |
// define the account username | |
public function get($account = "jpalala") | |
{ | |
if($account == '') { throw("MyTweets Error - no username"); } | |
// define the path to the feed of tweets | |
$path = "http://api.twitter.com/1/statuses/user_timeline.xml"; | |
// set the request for the API | |
$request = "?include_rts=true&screen_name=".$account."&count=5"; | |
// get the response from the API as an object | |
$tweet_list = simplexml_load_file($path.$request); | |
// check for Twitter posts | |
if ( count ( $tweet_list ) > 0 ) | |
{ | |
// define the array of tweets | |
$tweets = array(); | |
// loop through each Twitter post | |
foreach ( $tweet_list as $tweet ): | |
// format links to a clickable link | |
$tweet->text = preg_replace("/http:\/\/([^ ]+)/i", "<a href=\"http://$1\">http://$1</a>", $tweet->text); | |
// format @USERNAME into a link | |
$tweet->text = preg_replace("/@([^ ]+)/", "<a href=\"http://twitter.com/$1\" target=\"_blank\">@$1</a>", $tweet->text); | |
// add the tweet to the array of tweets | |
$tweets[] = array ( | |
'tweet' => (string) $tweet->text, | |
'posted' => (string) $tweet->created_at, | |
'image' => (string) $tweet->user->profile_image_url | |
); | |
endforeach; | |
// output how many tweets were loaded | |
$amount_tweets = count($tweets); | |
} else { | |
// output a message to show no tweets found | |
$amount_tweets = 0; | |
} | |
print '<style> | |
ul li{list-style:none;clear:both;overflow:auto;margin-bottom:10px;} | |
ul li span.img{float:left;width:48px;height:48px;background:green;} | |
ul li span.tweet{float:left;margin:5px 0 0 10px;} | |
ul li span.tweet span{color:#999;} | |
</style>'; | |
print '<ul>'; | |
foreach ( $tweets as $tweet ): | |
print '<li> | |
<span class="img"><img src="'. $tweet['image'] . '" /></span> | |
<span class="tweet">'. $tweet['tweet'].'<br /><span><?php echo $tweet['posted']; ?></span></span> | |
</li>'; | |
endforeach; | |
print '</ul>'; | |
print '<p><a style=\"color:lightblue;\" href="http://twitter.com/'.$account . '" target="_blank">@' .$account . '></a></strong></p>'; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment