Skip to content

Instantly share code, notes, and snippets.

@kwsim539
Created February 21, 2016 17:15
Show Gist options
  • Save kwsim539/4a61715796b574008113 to your computer and use it in GitHub Desktop.
Save kwsim539/4a61715796b574008113 to your computer and use it in GitHub Desktop.
PHP class to pull data from the Instagram API and return it as JSON code to parse with JavaScript
<?php
class getIgram
{
//Instagram Vars
private $myInstagramQuery;
private $myCacheFileIn;
private $myCacheCycleIn;
public function pullPosts($myInstagramQuery, $myCacheFileIn, $myCacheCycleIn)
{
// technically we don't need this really, but if you ever need other header info, this is the way
$setContextOptionsIn = array(
'http'=> array(
'method'=>"GET"
)
);
$createContextIn = stream_context_create($setContextOptionsIn);
// let's get our cache file, returns false if file does not exist
$getCacheFileModTimeIn = @filemtime( $myCacheFileIn );
if ( !$getCacheFileModTimeIn || ( time() - $getCacheFileModTimeIn >= $myCacheCycleIn) )
{
// go get me some json, returns false if error
$getInstagramData = file_get_contents($myInstagramQuery, false, $createContextIn);
if ($getInstagramData) {
// write the JSON to file, return it to the caller
file_put_contents( $myCacheFileIn, $getInstagramData );
$outputJSONIn = $getInstagramData;
}
else {
// uh oh, we have a problem, write some simple error json to tell us on the frontend
$errorArrayIn = array('error' => 'There was a problem getting data from the Instagram API, please try again.');
$outputJSONIn = json_encode($errorArray);
}
}
else
{
// get the cache file
$outputJSONIn = file_get_contents($myCacheFileIn);
}
$json_in=json_decode($outputJSONIn);
//instagram
$ivalue = 1;
foreach($json_in->data as $p)
{
$link = $p->link;
$style = ($ivalue%2==0) ? "black" : "white";
$instagramtime = $p->created_at;
$itime = date('jS F Y h:i:s A (T)', $instagramtime);
$newjsonIn[] = array('username'=> $p->user->username, 'image'=> $p->images->low_resolution->url, 'type'=> 'instagram', 'userid'=> $p->user->id, 'text'=> $p->caption->text, 'dataposted'=> $ttime, 'style'=> $style, 'id'=> $ivalue, 'sourcelink'=> $link);
$ivalue++;
}
return $newjsonIn;
}
}
$getIgram = new getIgram;
ob_start('ob_gzhandler');
header('Content-type: application/json');
echo json_encode($getIgram->pullPosts("https://api.instagram.com/v1/tags/PromJamSIMall/media/recent?client_id=08f21fad921a4792bedc400fa885903d","igram.json","60"));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment