php + json + twitter api
<?php
// define the parameters you want to use
$username = ‘richardmaisano’;
$tweet_count = ’10′;
// define the api url
$url = ‘https://api.twitter.com/1/statuses/user_timeline.json?screen_name=’ . $username . ‘&count=’ . $count . ‘&include_entities=1&include_rts=1′;
// define the cache file you created
$cache = dirname(__FILE__) . ‘/caches/twitter’;
// check to see if the cache is older than five minutes
// if so, refresh the data
$cache_time = filemtime($cache);
$five_minutes = time() – 300;
if ($cache_time > $five_minutes)
{
$data = file_get_contents($cache);
}
else
{
$data = file_get_contents($url);
$cachefile = fopen($cache, ‘wb’);
fwrite($cachefile, $data);
fclose($cachefile);
}
// set up the json return
$json = json_decode($data);
// the rest of the script just parses through the data,
// namely the date and time of tweet and any ‘entities’
if (!empty($json)) :
foreach ($json as $tweet) :
$datetime = $tweet->created_at;
$date = date(‘M d, Y’, strtotime($datetime));
$time = date(‘g:ia’, strtotime($datetime));
$tweet_text = $tweet->text;
// check if any entites exist and if so, replace then with hyperlinked versions
if (!empty($tweet->entities->urls) || !empty($tweet->entities->hashtags) || !empty($tweet->entities->user_mentions)) {
foreach ($tweet->entities->urls as $url) {
$find = $url->url;
$replace = ‘<a href="’.$find.’">’.$find.’</a>’;
$tweet_text = str_replace($find,$replace,$tweet_text);
}
foreach ($tweet->entities->hashtags as $hashtag) {
$find = ‘#’.$hashtag->text;
$replace = ‘<a href="http://twitter.com/#!/search/%23′.$hashtag->text.’">’.$find.’</a>’;
$tweet_text = str_replace($find,$replace,$tweet_text);
}
foreach ($tweet->entities->user_mentions as $user_mention) {
$find = "@".$user_mention->screen_name;
$replace = ‘<a href="http://twitter.com/’.$user_mention->screen_name.’">’.$find.’</a>’;
$tweet_text = str_ireplace($find,$replace,$tweet_text);
}
}
?>
<div class="entry tweet">
<span><?php echo $tweet_text; ?></span>
<div class="meta">
<small><?php echo $time; ?>, <?php echo $date; ?></small>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>

Processing your request, Please wait....
No Responses to “php + json + twitter api”
Comments (Your Comments)
Leave a Reply