I'm new to PHP and I can't figure out how to deal with Instagram APIs in order to (for example) extract a list of links to the standard resolution images by recent 3 items published by the user_id 3.
Here's what I created till now:
<?php
function get_instagram($user_id,$count)
{
$user_id = '3';
$count = '3';
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
$jsonData = $json_decode((file_get_contents($url)));
$data = $jsonData->data;
$result = '<ul>';
foreach ($data as $key => $value) {
$result .= '<li><a href='.$value->link.' ><img src="'.$value->images->standard_resolution->url.'" width="70" height="70" /></a></li> ';
}
$result .= '</ul>';
return $result;
}
The result is a blank page though.. can you help me?
You need to echo or do something with the returned data (Also you have a rouge $ in front of your json_decode function)
Try this:
<?php
function get_instagram($user_id=15203338,$count=6,$width=190,$height=190){
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
// Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}
$result = '<div id="instagram">'.PHP_EOL;
foreach ($jsonData->data as $key=>$value) {
$result .= "\t".'<a class="fancybox" data-fancybox-group="gallery"
title="'.htmlentities($value->caption->text).' '.htmlentities(date("F j, Y, g:i a", $value->caption->created_time)).'"
style="padding:3px" href="'.$value->images->standard_resolution->url.'">
<img src="'.$value->images->low_resolution->url.'" alt="'.$value->caption->text.'" width="'.$width.'" height="'.$height.'" />
</a>'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
return $result;
}
echo get_instagram();
?>
With $value->location->name
If you want to check its empty and if it is then dont show it but also want to append a string onto it if it is set you would do something like:
$location = (!empty($value->location->name))?'#'.$value->location->name:null;
Then use $location to echo where you want it.
I've extended the selected answer by writing a small script that can be used a boilerplate for anyone trying this.
It's setup with all the variables and starts with basic markup. Using selectors from Instagrams API docs you can build onto its output as needed.
This is built to be used specifically with WordPress with one small tweak to the image size conditional it can be used in any PHP application.
<?php
function instagram($count = 10, $width = 640, $height = 640) {
$user_id = 123456789;
$access_token = '123456789';
$size = wp_is_mobile() ? 'low_resolution' : 'standard_resolution';
$url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token='.$access_token.'&count='.$count;
$cache_location = './'.sha1($url).'.json';
$cache_time = '-1 hour';
if (file_exists($cache_location) && filemtime($cache_location) > strtotime($cache_time)) {
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache_location));
} else {
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache_location,json_encode($jsonData));
}
foreach ($jsonData->data as $key=>$value) {
echo '<div>';
echo '<img src="'.$value->images->$size->url.'"/>';
echo '</div>';
}
}
Basic Usage
<?php echo instagram(); ?>
Advanced Usage
<?php echo instagram($count = 1, $width = 100, $height = 100); ?>
Github Repo
Welp, This was working a week ago, but now, it gives me a PHP error:
"Message: Trying to get property of non-object"
on the line with the foreach statement: foreach ($jsonData->data as $key=>$value)
Turns out my JSON feed was actually corrupted, the captions to some of my instagrams were missing, so I had to add an if empty statement. I also am using a different method now, curious on your thoughts, works great!
<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/USER ID HERE/media/recent/?access_token=ACCES TOKEN HERE&count=14");
$cache = './instagram.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$instaData = json_decode(file_get_contents($cache));
} else {
$instaData = json_decode((file_get_contents($result)));
file_put_contents($cache,json_encode($instaData));
}
foreach ($instaData->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
echo '<a class="instagram-unit" target="blank" href="'.$post->link.'">
<img src="'.$post->images->low_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
<div class="instagram-desc">'.htmlentities($post->caption->text).' | '.htmlentities(date("F j, Y, g:i a", $post->caption->created_time)).'</div></a>';
}
}
?>
Related
I've been working on a movie review website and I can't quite get the calculate average rating functionality working. In the code below, In the first instance I am grabbing the current rating of the movie [$totalRating] via an API and setting the counter [$numRatings]. Then via an API I am collecting all of the ratings of that movie, attempting to to add them to the total rating, updating the counter within the loop.
However, when I rate movies they simply are updated to the registered rating (say I input an 8 it becomes an 8) and the division never takes place. Was wondering if anyone has any solutions or can see where I am going wrong?
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 1;
$totalRating = $baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (isset($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
$numRatings++;
$totalRating = $totalRating + $row['rating'];
}
}
$avgUserRating = $totalRating / $numRatings;
return $avgUserRating;
}
Might just need a small adjustment
function setUserRating($movieID)
{
$ep = "http://localhost:8888/MovieRating/api/?movieDetails=$movieID";
$response = file_get_contents($ep);
$Movies = json_decode($response, true);
$baseRating = $Movies[0]['movieRating'];
$numRatings = 0; //1
$totalRating = 0; //$baseRating;
$ep = "http://localhost:8888/MovieRating/api/?allMovieRatings=$movieID";
$resp = file_get_contents($ep);
$userRatings = json_decode($resp, true);
if (array_key_exists($userRatings['movie_ratings'])) {
$reviews = $userRatings['movie_ratings'];
}
if (isset($reviews)) {
foreach ($reviews as $row) {
++$numRatings;
$totalRating += $row['rating'];
}
}
return $numRatings > 0 ? $totalRating / $numRatings : $baseRating;
}
I'm trying to retrieve data from coinmarketcap's api and store the data to cache file. If the cache file is older than 10 minutes, retrieve new data and store to cache file. I have been able to get everything to work, except for caching the data. The cache file is never created in the plugin directory. Any help would be appreciated. Here is the code :
function Tickers($data){
foreach($data as $item){
echo "$item->symbol";
echo "<br>";
echo '<span>$' . $item->price_usd . '</span>';
echo "<br>";
echo "<br>";
}
}
function getdata(){
$time = 600; //seconds
$cache_file = 'wp-content/plugins/cryptocurrency_tickers/cache.txt';
if(file_exists($cache_file)){
if(time() - filemtime($cache_file) > $time) {
// too old , re-fetch
$data = json_decode(file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20'));
file_put_contents(cache_file,json_encode($data));
}
else{
//data is current
}
}else {
// create cache
$data = json_decode(file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20'));
file_put_contents(cache_file, json_encode($data));
}
$data = json_decode(file_get_contents($cache_file));
Tickers($data);
}
Look at your code again, missing '$' in front of 'cache_file' on file_put_contents
file_put_contents(cache_file,json_encode($data));
should be
file_put_contents($cache_file,json_encode($data));
Also when you get the json data from the API first you decode, then encode, why you didn't save the data directly from the API, it's already json encoded.
Better version of your code:
function Tickers($data){
foreach($data as $item){
echo "$item->symbol";
echo "<br>";
echo '<span>$' . $item->price_usd . '</span>';
echo "<br>";
echo "<br>";
}
}
function getdata(){
$time = 600; //seconds
$cache_file = '/path/to/cache.txt';
if(file_exists($cache_file)){
if(time() - filemtime($cache_file) > $time) {
// too old , re-fetch
$data = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20');
file_put_contents($cache_file, $data);
} else{
//data is current
}
} else {
// create cache
$data = file_get_contents('https://api.coinmarketcap.com/v1/ticker/?limit=20');
file_put_contents($cache_file, $data);
}
$data = json_decode(file_get_contents($cache_file));
Tickers($data);
}
getdata();
Also make sure the plugin directory is writable by your web server user.
I am pulling a report using the Adobe API from Omniture.
Here is the full script :
<?php
include_once('/path/SimpleRestClient.php');
// Date
$end_date = date("Y-m-d",strtotime("-1 days"));
$start_date = date("Y-m-d",strtotime("-8 days"));
// Location of the files exported
$adobe_file = '/path/Adobe_'.$end_date.'.csv';
// List creation that will be updated with the fields and be put into my CSV file
$list = array
(
array('lasttouchchannel', 'product','visits','CTR(Clicks/PageViews)') // headers // ADD or DELETE metrics #
);
function GetAPIData($method, $data)
{
$username = "XXXX";
$shared_secret = "XXXX";
$postURL = "https://api3.omniture.com/admin/1.4/rest/?method=";
// Nonce is a simple unique id to each call to prevent MITM attacks.
$nonce = md5(uniqid(php_uname('n'), true));
// The current timestamp in ISO-8601 format
$nonce_ts = date('c');
/* The Password digest is a concatenation of the nonce, it is timestamp and your password
(from the same location as your username) which runs through SHA1 and then through a base64 encoding */
$digest = base64_encode(sha1($nonce . $nonce_ts . $shared_secret));
$rc = new SimpleRestClient();
$rc -> setOption(CURLOPT_HTTPHEADER, array("X-WSSE: UsernameToken Username=\"$username\", PasswordDigest=\"$digest\", Nonce=\"$nonce\", Created=\"$nonce_ts\""));
//var_dump($o);
$rc -> postWebRequest($postURL .$method, $data);
return $rc;
}
$method = 'Report.Queue';
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
/*
"date":"'.$date.'",
"dateTo":"'.$date.'",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
*/
$rc=GetAPIData($method, $data);
if($rc -> getStatusCode() == 200) // status code 200 is for 'ok'
{
$counter = 0;
do
{
if($counter>0){sleep($sleep = 120);}
$return = GetAPIData('Report.Get', $rc->getWebResponse());
$counter++;
}while($return -> getStatusCode() == 400 && json_decode($return->getWebResponse())->error == 'report_not_ready'); // status code 400 is for 'bad request'
//
$json=json_decode($return->getWebResponse());
foreach ($json->report->data as $el)
{
echo $el->name.":".$el->counts[0].":".$el->counts[1]."\n";
// Adding the data in the CSV file without overwriting the previous data
array_push($list, array($el->name, $el->name, $el->counts[0], ($el->counts[1])/($el->counts[2])));
}
}
else
{
echo "Wrong";
}
$fp = fopen($adobe_file, 'w');
foreach ($list as $fields)
{
// Save the data into a CSV file
fputcsv($fp, $fields);
}
fclose($fp);
?>
How can I get the names of the metrics and elements in order to use them in this script? There is no way. I searched with all the possible tags on google and nothing worked !
I need the metrics and elements for this part of the code :
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
I cannot find 'date' as an element which is crucial. I cannot find all the other metrics as well. In Google Analytics we had this link :
Google Analytics Query
but in Adobe there is not any. I want something like that :
"metrics":[{"id":"instances"},{"id":"impressions"}],
"elements":[{"id":"date","top":"50000"}]
You would json_decode() as $data contains a JSON string. For example:
$data ='
{
"reportDescription":
{
"reportSuiteID":"XXXX",
"dateFrom":"'.$start_date.'",
"dateTo":"'.$end_date.'",
"metrics":[{"id":"visits"},{"id":"instances"},{"id":"pageviews"}],
"elements":[{"id":"lasttouchchannel","top":"50000"}]
}
}';
$json = json_decode($data, true);
echo $json['reportDescription']['dateFrom'];
print_r($json['reportDescription']['metrics']);
I want to display the Facebook comment count on my blog archives.
My wordpress site has the following php function in function.php
// Get combined FB and WordPress comment count
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
$wpCount = get_comments_number();
$realCount = $count + $wpCount;
if ($realCount == 0 || !isset($realCount)) {
$realCount = 0;
}
return $realCount;
}
This is how I am using the function on a template file inside a loop <?php echo full_comment_count(); ?>
Most of the time most of the articles show "0" comments. But sometime one or 2 of them work. what am i doing wrong
Try this
function full_comment_count() {
global $post;
$url = get_permalink($post->ID);
$filecontent = file_get_contents('https://graph.facebook.com/?ids=' . $url);
$json = json_decode($filecontent);
$count = $json->$url->comments;
if ($count == 0 || !isset($count)) {
$count = 0;
}
echo $count;
}
Here's a sample of a JSON entry output from Feedbin's entries.json:
[
{
"id": 2077,
"title": "Objective-C Runtime Releases",
"url": "http:\/\/mjtsai.com\/blog\/2013\/02\/02\/objective-c-runtime-releases\/",
"author": "Michael Tsai",
"content": "<p><a href=\"https:\/\/twitter.com\/bavarious\/status\/297851496945577984\">Bavarious<\/a> created a <a href=\"https:\/\/github.com\/bavarious\/objc4\/commits\/master\">GitHub repository<\/a> that shows the differences between versions of <a href=\"http:\/\/www.opensource.apple.com\/source\/objc4\/\">Apple\u2019s Objective-C runtime<\/a> that shipped with different versions of Mac OS X.<\/p>",
"summary": "Bavarious created a GitHub repository that shows the differences between versions of Apple\u2019s Objective-C runtime that shipped with different versions of Mac OS X.",
"published": "2013-02-03T01:00:19.000000Z",
"created_at": "2013-02-04T01:00:19.127893Z"
}
]
Here's my function which authenticates with Feedbin's API, retrieves the JSON document, and prints title and URL for the first 5 results.
<?php
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'username'; // authentication
$password = 'password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
$cache_feedbin = '/BLAHBLAH/'.sha1($json_url).'.json';
if(file_exists($cache_feedbin) && filemtime($cache_feedbin) > time() - 1000){
// if a cache file newer than 1000 seconds exist, use it
$data_feedbin = file_get_contents($cache_feedbin);
} else {
$data_feedbin = $result;
file_put_contents($cache_feedbin, $data_feedbin);
}
foreach (array_slice(json_decode($data_feedbin), 0, 5) as $obj) {
$feedbin_title = $obj->title;
$feedbin_url = $obj->url;
echo '<li>', $feedbin_title, '</li>';
}
?>
It works like a charm. What I'd love to try is mixing this with unread_entries.json, which retuns an array of entry_ids of unread items. Something like:
[4087,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097]
My goal is: check within the foreach which IDs match with the IDs of unread items taken from unread_entries.json. For the IDs that match (so, unread items) do nothing, for ALL THE OTHERS, display an image which says "READ".
BONUS ROUND:
Updated example to include a function for caching JSON requests:
define('CACHE_PATH', '/tmp'); // Might want to change this
define('CACHE_SECS', 1000);
define('API_USERNAME', 'username');
define('API_PASSWORD', 'password');
$entries = fetchJSON('https://api.feedbin.me/v2/entries.json', API_USERNAME, API_PASSWORD, CACHE_SECS);
$unread_msgs = fetchJSON('https://api.feedbin.me/v2/unread_entries.json', API_USERNAME, API_PASSWORD, CACHE_SECS);
foreach ($entries as $obj) {
$is_read = !in_array($obj->id, $unread_msgs); // Read if not present in unread
$feedbin_title = $obj->title;
$feedbin_url = $obj->url;
$output = '<li><a href="'.$feedbin_url.'">'. $feedbin_title;
if ($is_read) {
$output .= ' <img src="icon-read.png" title="READ" />';
}
$output .= '</a></li>';
echo $output;
}
/** Return a JSON decoded object/array */
function fetchJSON($json_url, $username = null, $password = null, $cache_secs = null) {
$cache_file = CACHE_PATH.'/'.sha1($json_url).'.json';
$data = null;
// Check if we need to request new content
if (!$cache_secs || !file_exists($cache_file) || filemtime($cache_file) < time() - $cache_secs) {
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// If username given add to curl opts
if (!empty($username)) {
$options[CURLOPT_USERPWD] = $username . ":" . $password;
}
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$data = curl_exec($ch); // Getting JSON result string
curl_close($ch);
if ($cache_secs) {
file_put_contents($cache_file, $data);
}
} else {
// Got data from the cache
$data = file_get_contents($cache_file);
}
return !empty($data) ? json_decode($data) : null;
}
$ids = [4087,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097];
$id = 4087;
if (isset($ids[$id]) )
{
echo "do something\n";
}
else
{
echo "do something else\n";
}