I've been reading more on PHP JSON and APIs I wanted to play around and pull a user's tweets so I wrote a function that requires the TwitterAPIExchange wrapper.
The code:
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
get_twitter_json();
function get_twitter_json() {
$username = 'foobar';
$count = 5;
$json_folder = 'json';
$pull_time = 1;
$settings = array(
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
);
if (is_dir($json_folder)) :
echo "Directory $json_folder exists<br />";
else :
echo "Did NOT find directory $json_folder<br />";
exit();
endif;
$file_loc = "json/twitter.json";
$cachetime = @filemtime($file_loc);
$diff = time() - $cachetime;
if ($diff <= 60 * $pull_time) :
$results = json_decode(file_get_contents($file_loc));
else :
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = '?screen_name=' . $username . '&count=' . $count;
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$results = json_decode(
$twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(), true
);
$i = 0;
if (isset( $results['error'])) :
echo 'Issue found in request';
exit();
else :
foreach($results as $tweet) :
$tweets[$i]['created'] = $tweet['created_at'];
$tweets[$i]['text'] = $tweet['text'];
$tweets[$i]['username'] = $tweet['user']['name'];
$tweets[$i]['screenname'] = $tweet['user']['screen_name'];
$tweets[$i]['url'] = $tweet['user']['url'];
$i++;
endforeach;
endif;
$jsonified = json_encode($tweets);
$jsoncache = $file_loc;
$fp = fopen($jsoncache, "w");
fwrite($fp, $jsonified);
fclose($fp);
endif;
}
Are there any improvements I can make to my code? Eventually I will implement this into a WordPress Plugin. I am curious about any better approaches than fwrite
and fclose
so if there is a better way to write to a JSON file that would be helpful.