Wedge

Public area => The Pub => Off-topic => Topic started by: MultiformeIngegno on April 18th, 2012, 08:59 PM

Title: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 18th, 2012, 08:59 PM
Hi guys! :)
I'm trying to display a number of recent photos from Instagram that have a certain tag (for example: "snow").

I have never done this before (and I have PHP and JSON knowledge equal to 0,1.. :P ) + saying that Instagram API's documentation is poor is a gift!!

Here's the code I'm trying..

Code: [Select]
<?php 
$json 
file_get_contents('https://api.instagram.com/v1/tags/snow/media/recent?client_id=XXX'); 
$decode json_decode($jsontrue); 
var_dump($decode); 
?>

<?php 
    
foreach ($response['data'] as $data) { 
        
$thumbnail $data['images']['low_resolution']['url']; 
        
$author $data['caption']['from']['username']; 
        
$date $data['created_time']; 
        
$text $data['caption']['text']; 
        
$link $data['link']; }
    
?>

    <div>
        <a href="<?php $link ?>"><span></span><img src="<?php $thumbnail ?>" title="<?php $text ?>" alt="<?php $text ?>" /></a>

        <div>via <?php $author ?> at <?php echo date("h:i:s A \o\\n d/m/Y",$date); ?></div>
        <?php $text ?>
</div>

Ehm.. (of course?) it doesn't work.. do you have an idea of what I need to change?

Thankssss ;)

EDIT: XXX is the client ID I have.
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 18th, 2012, 09:03 PM
First of all, what do you mean by 'it doesn't work'. Secondly, where is their API documentation, what's the structure of the API that this is supposed to interact with?
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 18th, 2012, 09:48 PM
This is a piece of the very long code I get if I visit the file_get_contents URL (after adding the Client ID/token):
Code: [Select]
{"pagination":{"next_max_tag_id":"1334803018782","deprecation_warning":"next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead","next_max_id":"1334803018782","next_min_id":"1334803397349","min_tag_id":"1334803397349","next_url":"https:\/\/api.instagram.com\/v1\/tags\/snow\/media\/recent?client_id=3d61d317425440a1aee6c9b795b0fe92&max_tag_id=1334803018782"},"meta":{"code":200},"data":[{"tags":["horses","centreparcs","snow","santa","winter"],"location":{"latitude":51.1865,"longitude":-2.2355},"comments":{"count":1,"data":[{"created_time":"1334778197","text":"#winter #centreparcs #horses #santa #snow","from":{"username":"mattpeno","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_22685403_75sq_1334421562.jpg","id":"22685403","full_name":"Matt Penistone"},"id":"172454476287201505"}]},"filter":"Lord Kelvin","created_time":"1334778119","link":"http:\/\/instagr.am\/p\/JkrdZ7BlKe\/","likes":{"count":0,"data":[]},"images":{"low_resolution":{"url":"http:\/\/distilleryimage6.instagram.com\/90185cf0898e11e1a87612313804ec91_6.jpg","width":306,"height":306},"thumbnail":{"url":"http:\/\/distilleryimage6.instagram.com\/90185cf0898e11e1a87612313804ec91_5.jpg","width":150,"height":150},"standard_resolution":{"url":"http:\/\/distilleryimage6.instagram.com\/90185cf0898e11e1a87612313804ec91_7.jpg","width":612,"height":612}},"caption":{"created_time":"1334778134","text":"Snow horse","from":{"username":"mattpeno","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_22685403_75sq_1334421562.jpg","id":"22685403","full_name":"Matt Penistone"},"id":"172453947268026590"},"type":"image","id":"172453822445539998_22685403","user":{"username":"mattpeno","website":"","bio":"\ud83d\udc7ffun loving\ud83d\udc9a\r\n\ud83d\ude32punk rocking\ud83d\udc7d\r\n\ud83d\udc38spaceship flying\ud83d\ude80\r\n\ud83d\ude1ccider drinking\ud83c\udf7a\r\n27 year old something..","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_22685403_75sq_1334421562.jpg","full_name":"Matt Penistone","id":"22685403"}},{"tags":["switzerland","snow","winter","forest"],"location":null,"comments":{"count":0,"data":[]},"filter":"Amaro","created_time":"1334775900","link":"http:\/\/instagr.am\/p\/JknOf2u8TC\/","likes":{"count":1,"data":[{"username":"martinboygaard","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_22343546_75sq_1333840303.jpg","id":"22343546","full_name":"Martin B\u00f8ygaard"}]},"images":{"low_resolution":{"url":"http:\/\/distilleryimage10.instagram.com\/654e02c2898911e1af7612313813f8e8_6.jpg","width":306,"height":306},"thumbnail":{"url":"http:\/\/distilleryimage10.instagram.com\/654e02c2898911e1af7612313813f8e8_5.jpg","width":150,"height":150},"standard_resolution":{"url":"http:\/\/distilleryimage10.instagram.com\/654e02c2898911e1af7612313813f8e8_7.jpg","width":612,"height":612}},"caption":{"created_time":"1334778184","text":"#forest #snow #winter #switzerland","from":{"username":"sharkypowaaa","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_37503824_75sq_1334745578.jpg","id":"37503824","full_name":"sharkypowaaa"},"id":"172454365510747828"},"type":"image","id":"172435205837800642_37503824","user":{"username":"sharkypowaaa","website":"","bio":"","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_37503824_75sq_1334745578.jpg","full_name":"sharkypowaaa","id":"37503824"}},{"tags":["snow"],"location":null,"comments":{"count":1,"data":[{"created_time":"1334778181","text":"#snow","from":{"username":"mosodal","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_32258055_75sq_1333988855.jpg","id":"32258055","full_name":"Monika"},"id":"172454342583894661"}]},"filter":"Valencia","created_time":"1334778146","link":"http:\/\/instagr.am\/p\/JkrgqML8BM\/","likes":{"count":0,"data":[]},"images":{"low_resolution":{"url":"http:\/\/distilleryimage0.instagram.com\/9ffbeb50898e11e19e4a12313813ffc0_6.jpg","width":306,"height":306},"thumbnail":{"url":"http:\/\/distilleryimage0.instagram.com\/9ffbeb50898e11e19e4a12313813ffc0_5.jpg","width":150,"height":150},"standard_resolution":{"url":"http:\/\/distilleryimage0.instagram.com\/9ffbeb50898e11e19e4a12313813ffc0_7.jpg","width":612,"height":612}},"caption":{"created_time":"1334778159","text":"Ja, jeg hadde s\u00e5 lyst p\u00e5 sn\u00f8 n\u00e5.","from":{"username":"mosodal","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_32258055_75sq_1333988855.jpg","id":"32258055","full_name":"Monika"},"id":"172454157078217347"},"type":"image","id":"172454046071767116_32258055","user":{"username":"mosodal","website":"","bio":"jente, 17 \u00e5r, NORGE :-) ","profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_32258055_75sq_1333988855.jpg","full_name":"Monika","id":"32258055"}},{"tags":["bradford","igerseurope","igersportugal","snow","statigram"],"location":null,"comments":{"count":0,"data":[]},"filter":"Lord Kelvin","created_time":"1334778177","link":"http:\/\/instagr.am\/p\/JkrkgxvQZ8\/","likes":{"count":0,"data":[]},"images":{"low_resolution":{"url":"http:\/\/distilleryimage8.instagram.com\/b2cc04ea898e11e1989612313815112c_6.jpg","width":306,"height":306},"thumbnail":{"url":"http:\/\/distilleryimage8.instagram.com\/b2cc04ea898e11e1989612313815112c_5.jpg","width":150,"height":150},"standard_resolution":{"url":"http:\/\/distilleryimage8.instagram.com\/b2cc04ea898e11e1989612313815112c_7.jpg","width":612,"height":612}},"caption":{"created_time":"1334778178","text":"#igersportugal #snow #igerseurope #bradford #statigram","from":

I said it doesn't work because with the code I mentioned in the previous post I get this:
multiformeingegno.it/wp-content/themes/multiformeingegno/test.php
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 18th, 2012, 09:51 PM
If you visit the file_get_contents URL, you should expect to get some JSON. The code you get is some JSON.

So, again, what is it supposed to do that it is not doing? Or what is it doing that it is not supposed to?

Showing me a bunch of code, showing me another bunch of code, I have no idea what you're supposed to be getting, but hey, I'm sure we'll figure it out when you tell me these things...
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 18th, 2012, 10:06 PM
Quote from Arantor on April 18th, 2012, 09:51 PM
Showing me a bunch of code, showing me another bunch of code, I have no idea what you're supposed to be getting, but hey, I'm sure we'll figure it out when you tell me these things...
Ok, let's try. :P
I want to extract data from the JSON file (the one in file_get_contents). It "outputs" new stuff every time that users post images with the "snow" tag (in this case), always with the same structure, for example:
{"username":"XXX","profile_picture":"XXX","id":"XXX","full_name":"XXX"},"id":"XXX"}]},,"images":{"low_resolution":{"url":"http:XXX","width":XXX,"height":XXX},"thumbnail":{"url":"http:XXX","width":XXX,"height":XXX:" etc...

I need to extract some of these information. For example I may want to extract and display username and low res URL only for every entry.

P.S.: Posts preview is broken.. :whistle:
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 18th, 2012, 10:14 PM
Quote
I want to extract data from the JSON file (the one in file_get_contents). It "outputs" new stuff every time that users post images with the "snow" tag (in this case), always with the same structure, for example:
Without being funny, am I not making myself clear? I know what you're doing. I know what you're trying to do. You want me to help you with your code. The code is not acting as it should. What it is doing that is different to what you want?

Right now, we're at the equivalent of you going to the doctor, and explaining your life history and goals. You haven't yet described your problem or its symptoms, merely that you're ill.
Quote
P.S.: Posts preview is broken..
Define broken.
Title: Re: Extract images with a certain tag from Instagram
Post by: billy2 on April 18th, 2012, 10:17 PM
Agree, post preview doesn't display
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 18th, 2012, 10:51 PM
Quote from Arantor on April 18th, 2012, 10:14 PM
The code is not acting as it should. What it is doing that is different to what you want?
Well, this is the code (simplifed):
Code: [Select]
<?php 
$json 
file_get_contents('https://api.instagram.com/v1/tags/snow/media/recent?client_id=XXX'); 
$decode json_decode($jsontrue); 
var_dump($decode); 
?>

<?php 
    
foreach ($decode['data'] as $data) { 
        
$thumbnail $data['images']['low_resolution']['url']; 
}
    
?>

    <div>
        <img src="<?php $thumbnail ?>" alt="" />
</div>

It outputs(http://multiformeingegno.it/wp-content/themes/multiformeingegno/test.php) ALL the JSON file (because of the file_get_contents). I want just the $thumbnail variable for each entry. :)
There's something wrong with the foreach(). At the end of the file I get: Warning: Invalid argument supplied for foreach()
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 19th, 2012, 12:55 AM
Uhm.. look at this other piece of code:
Code: [Select]
<?php
$instagramClientID 
'9110e8c268384cb79901a96e3a16f588';
$api 'https://api.instagram.com/v1/tags/snow/media/recent?client_id='.$instagramClientID//api request (edit this to reflect tags)
$response file_get_contents($api,0,null,null);

$instagrams json_decode($response)->data;

$features = array();
foreach ( 
$instagrams as $instagram ) {
    
$features[] = array(
        
'properties' => array(
            
'image' => $instagram->images->standard_resolution->url,
            
'description' => $instagram->caption $instagram->caption->text null,
        )
    );
}

$results = array(
    
'features' => $features,
);

print_r($results);

?>


Instead of print_r($results); I'd like to have the ability to output something like:
<img src="<?php $image ?>" alt="<?php $description ?>" />

The problem is how can I specify which parameter of which entry needs to be shown..?
The result should be something like <img src="IMAGE 1" alt="DESCRIPTION1" /><img src="IMAGE 2" alt="DESCRIPTION2" /><img src="IMAGE 3" alt="DESCRIPTION3" />
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 19th, 2012, 03:18 AM
I studied JSON a bit and managed to create a "twitter widget" (okay I copied the part for($i=0;$i<$count;$i++), the rest is mine tough :P):
Code: [Select]
<?php
$json file_get_contents("http://twitter.com/status/user_timeline/lorenzoraffio.json?count=10"true);
$decode json_decode($jsontrue);
echo "
<ul style='color:#6E6E6E'>"
;
$count count($decode); //counting the number of status
$date $tweets['created_at']; // created date
for($i=0;$i<$count;$i++){ echo '
<li>'
.$decode[$i]['text'].'<br><a href='; echo '"http://twitter.com/#!/'.$decode[0][user][name].'/status/'.$decode[$i][id].'"><small>'date('j F',strtotime($decode[$i]['created_at'])) ."</small></a> - <a href='http://twitter.com/intent/tweet?in_reply_to=".$decode[$i][id]."'><small>rispondi</small></a> - <a href='http://twitter.com/intent/retweet?tweet_id=".$decode[$i][id]."'><small>retweet</small></a> - <a href='http://twitter.com/intent/favorite?tweet_id=".$decode[$i][id]."'><small>preferito</small></a></li>";} echo "
</ul>
"
;
?>


And this works!! ;)

The problem is that I tried to do the same for Instagram (replacing the parameters) but seems more complicated...!
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 19th, 2012, 01:00 PM
Well it WILL output everything, since you have the var_dump in there...
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 19th, 2012, 04:40 PM
This should be better, no?
Code: [Select]
<?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>';
echo $result;
}

Result is blank page though... :blush:
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 19th, 2012, 06:00 PM
Yayyyy!! This works!!!! ;) ;)

Code: [Select]
function get_instagram($user_id=3,$count=3,$width=70,$height=70){

    $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)));
    $result = '<ul>'.PHP_EOL;
    foreach ($jsonData->data as $key=>$value) {
        $result .= "\t".'<li><a href="'.$value->link.'"><img src="'.$value->images->standard_resolution->url.'" width="'.$width.'" height="'.$height.'" /></a></li>'.PHP_EOL;
    }
    $result .= '</ul>'.PHP_EOL;
    return $result;
}

echo get_instagram();

Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 19th, 2012, 06:14 PM
Added the cache:
Code: [Select]
function get_instagram($user_id=3,$count=3,$width=70,$height=70){

    $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 = '<ul>'.PHP_EOL;
    foreach ($jsonData->data as $key=>$value) {
        $result .= "\t".'<li><a href="'.$value->link.'"><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" /></a></li>'.PHP_EOL;
    }
    $result .= '</ul>'.PHP_EOL;
    return $result;
}

echo get_instagram();
Title: Re: Extract images with a certain tag from Instagram
Post by: Nao on April 19th, 2012, 06:18 PM
How come I never heard about Amstamgram before they got gobbled up by Facebook? :P
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:00 AM
Quote from Nao on April 19th, 2012, 06:18 PM
How come I never heard about Amstamgram before they got gobbled up by Facebook? :P
Eh eh! I knew it already.. anyway this acquisition made it of course more and more famous. ;)

Okay.. now that I managed to get it working I.. have another question. :P
I'm using this code to create a list of tweets from my Twitter account:
Code: [Select]
<?php
$json wp_remote_get("http://twitter.com/status/user_timeline/lorenzoraffio.json?count=6"true);
$decode json_decode($json['body'], true);
echo "
<ul style='color:#6E6E6E'>"
;
$count count($decode); //counting the number of status
$date $tweets['created_at']; // created date
for($i=0;$i<$count;$i++){ echo '
<li>'
.$decode[$i]['text'].'<br><a href='; echo '"http://twitter.com/#!/'.$decode[0][user][name].'/status/'.$decode[$i][id].'"><small>'date('j F',strtotime($decode[$i]['created_at'])) ."</small></a> - <a href='http://twitter.com/intent/tweet?in_reply_to=".$decode[$i][id]."'><small>rispondi</small></a> - <a href='http://twitter.com/intent/retweet?tweet_id=".$decode[$i][id]."'><small>retweet</small></a> - <a href='http://twitter.com/intent/favorite?tweet_id=".$decode[$i][id]."'><small>preferito</small></a></li>";} echo "
</ul>
"
;
?>


Everything works perfectly except that the dates are in english. I need to set italian language for the strtotime function.. I know I need to use setlocale(LC_TIME, 'it_IT'); but I don't know where to add it..
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:10 AM
You can add the setlocale call first before the wp_remote_get call if you like.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:14 AM
Uhm.. dates are still in english..
Code: [Select]
<?php
setlocale(LC_TIME'it_IT');
$json wp_remote_get("http://twitter.com/status/user_timeline/lorenzoraffio.json?count=6"true);
$decode json_decode($json['body'], true);
echo "
<ul style='color:#6E6E6E'>"
;
$count count($decode); //counting the number of status
$date $tweets['created_at']; // created date
for($i=0;$i<$count;$i++){ echo '
<li>'
.$decode[$i]['text'].'<br><a href='; echo '"http://twitter.com/#!/'.$decode[0][user][name].'/status/'.$decode[$i][id].'"><small>'date('j F',strtotime($decode[$i]['created_at'])) ."</small></a> - <a href='http://twitter.com/intent/tweet?in_reply_to=".$decode[$i][id]."'><small>rispondi</small></a> - <a href='http://twitter.com/intent/retweet?tweet_id=".$decode[$i][id]."'><small>retweet</small></a> - <a href='http://twitter.com/intent/favorite?tweet_id=".$decode[$i][id]."'><small>preferito</small></a></li>";} echo "
</ul>
"
;
?>


And another question.. would it be faster (and better) to use file_get_contents or wp_remote_get (a WP function that uses the HTTP GET method..)? :)
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:27 AM
http://php.net/manual/en/function.date.php:
Quote
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:34 AM
Code: [Select]
<?php
setlocale(LC_TIME'it_IT');
$json wp_remote_get("http://twitter.com/status/user_timeline/lorenzoraffio.json?count=6"true);
$decode json_decode($json['body'], true);
echo "
<ul style='color:#6E6E6E'>"
;
$count count($decode); //counting the number of status
$date $tweets['created_at']; // created date
for($i=0;$i<$count;$i++){ echo '
<li>'
.$decode[$i]['text'].'<br><a href='; echo '"http://twitter.com/#!/'.$decode[0][user][name].'/status/'.$decode[$i][id].'"><small>'date('j F',strftime($decode[$i]['created_at'])) ."</small></a> - <a href='http://twitter.com/intent/tweet?in_reply_to=".$decode[$i][id]."'><small>rispondi</small></a> - <a href='http://twitter.com/intent/retweet?tweet_id=".$decode[$i][id]."'><small>retweet</small></a> - <a href='http://twitter.com/intent/favorite?tweet_id=".$decode[$i][id]."'><small>preferito</small></a></li>";} echo "
</ul>
"
;
?>


Warning: date() expects parameter 2 to be long :blush:
I'm doing it wrong.. right? :P
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:42 AM
Yes, you're doing it wrong. Don't use date, as I said, it doesn't do what you want. And plugging in strftime has broken it because date wants a number, not a string, hence the error.

Code: [Select]
strftime('%e %B',strtotime($decode[$i]['created_at']))

It won't work on Windows, though as %e isn't supported.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:48 AM
Oh! Clear now. :)
Am I wrong or the line $date = $tweets['created_at']; is useless (because then I decode the date directly from the JSON)..? It confused me a bit... I thought I needed to change that too but then I realized I don't need that... Right?
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:49 AM
Yup, it is useless, unless you want to directly use $date itself into the echo statement.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:52 AM
Clear. :)

And about..:
Quote from MultiformeIngegno on April 20th, 2012, 02:14 AM
would it be faster (and better) to use file_get_contents or wp_remote_get (a WP function that uses the HTTP GET method..)?
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:58 AM
Considering that I have no idea what wp_remote_get does (and note that file_get_contents with the URL wrapper does also use the HTTP GET method), I cannot answer that question, and no, I'm not about to trawl through the shit-heap that is WP's source to find out.

What I can tell you is that if file_get_contents works, it's certainly workable. But it has limitations, namely that it's not particularly flexible across servers since it's easy to disable it at the config level, and it isn't robust in terms of handling time-outs. If WP's function handles *any* of that (and even my lack of faith in WP's code suggests that it would handle *some* of it), run with it.

If this were file_get_contents vs Wedge's equivalent (the weget class), I'd have no hesitation in recommending Wedge's own much lengthier and likely slower - but far far more robust solution. I would likely argue the same for WP's case.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:20 PM
Reasonable. :)

I "applied" htmlentities to my decoded data: '.htmlentities($value->caption->text).'
The downside is that accents are broken, example:  ì becomes Ã~

Page char-set is UTF-8. I thought it would have handled accented chars properly...!
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:22 PM
The incoming data isn't UTF-8, it's probably likely ISO-8859-1.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 02:32 PM
This code works, is it also correct? :)
'.htmlentities($value->caption->text, ENT_QUOTES, "UTF-8").'
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 02:35 PM
If it works, it's probably correct... ;)
Title: Re: Extract images with a certain tag from Instagram
Post by: PantsManUK on April 20th, 2012, 05:02 PM
Quote from Nao on April 19th, 2012, 06:18 PM
How come I never heard about Amstamgram before they got gobbled up by Facebook? :P
TBH, it was a niche app at best before they released the Mandroid version (and got bought by Facebook).
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 06:12 PM
Ok, another problem.. :P
Instagram created_time timestamp is GMT (I presume.. :P).. I need to get the italian timezone..

So I changed this:
Code: [Select]
'.htmlentities(strftime('%e %B %Y alle %R', $value->caption->created_time)).'

to:
Code: [Select]
'.htmlentities(gmstrftime('%e %B %Y alle %R',time()+3600,$value->caption->created_time)).'

But I get:
Warning: gmstrftime() expects at most 2 parameters, 3 given
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 06:27 PM
I do get so confused in trying to decipher the mindfuck that is time and date in PHP.

I'm confused why you're putting in time() + 3600. gmstrftime as PHP's manual says wants two parameters - the format you want to display and the time you want to display in that format, putting in time() + 3600 is just going to confuse it (and it complains)

The description seems to indicate that it would actually deal with the offset itself (since setlocale should be providing it), which would suggest simply:
Code: [Select]
'.htmlentities(gmstrftime('%e %B %Y alle %R', $value->caption->created_time)).'

Failing that, the more naive but workable solution (though won't take into account DST)
Code: [Select]
'.htmlentities(strftime('%e %B %Y alle %R', $value->caption->created_time + 3600)).'
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 06:40 PM
Second solution worked. :)

To change the "caching time" to ~16 min instead of 1 hour I need to change this:
Code: [Select]
if(file_exists($cache) && filemtime($cache) > time() - 60*60)

to:
Code: [Select]
if(file_exists($cache) && filemtime($cache) > time() - 100*10)

..? 100*10 are seconds, right?
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 06:41 PM
Yes, time() and filemtime() work on seconds.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 06:53 PM
Is there a sense to have 60*60 instead of simply 3600? :o
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 06:56 PM
Only for readability later on. Using 3600 will be faster than using 60*60, but 60*60 is more readable. Unless we're talking an insanely busy site it doesn't matter (and if we are, there are bigger things to worry about than that anyway)
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 08:40 PM
Do you think that 500 seconds (8 minutes) is a time too short and will impact on the server..?
I don't think it is.. also because the file cached is smaller than 10kb..
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 08:42 PM
So you're fetching tags from Instagram... how often are items posted from Instagram that fit your tags?

If they're posted every 5 minutes or so, 3-4 minutes (180-240 seconds) is fine, if they're posted every 10 minutes, 8 minutes of cache is fine.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 08:48 PM
Quote from Arantor on April 20th, 2012, 08:42 PM
So you're fetching tags from Instagram... how often are items posted from Instagram that fit your tags?
Uhm.. not really 5 or 10 minutes..it's a unused tag (#bombacarta) and it's used only by our "organization".. I presume that there will be a new image every.. day? or every 2 days..?

What's a good timing..?

And what if I was extracting photos only from MY recent photos (only photos by the user_id xxx) instead of tags (i.e. there are no other images to "discard", every photo in the provided stream has to be shown)? Would this be better? :)
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 08:57 PM
If you're talking about one a day or thereabouts, there's really no need to be fetching any more frequently than perhaps once every 12 hours, or if you're really bothered, 1 to 6 hours.

I can't tell you whether using your account vs tags would be better. Which better describes what you want to show?
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 20th, 2012, 09:15 PM
Quote from Arantor on April 20th, 2012, 08:57 PM
If you're talking about one a day or thereabouts, there's really no need to be fetching any more frequently than perhaps once every 12 hours, or if you're really bothered, 1 to 6 hours.
Uhm, I know but doing so I have to wait 12 hours to see the image on the website after I took it. Right..? I'd like to have max 10/15 min delay... do you think it's not possible?
Quote
I can't tell you whether using your account vs tags would be better. Which better describes what you want to show?
I asked that because I have 2 sites where I'm using this snippet. The first retrieves the images of my user_id stream only, the other retrieves photos with a certain tag (so it has to scan every photo to ensure they have or not my tag, I presume). So I was wondering if the user-stream only snippet is less intrusive for the server because it has to scan a stream only.
Title: Re: Extract images with a certain tag from Instagram
Post by: Arantor on April 20th, 2012, 09:31 PM
Quote
Uhm, I know but doing so I have to wait 12 hours to see the image on the website after I took it. Right..? I'd like to have max 10/15 min delay... do you think it's not possible?
And therein lies the problem. Your code is passive, it's doing lookups to see if there's something new. So if you want it to appear with no more than 10 minutes delay, that's the maximum caching time. But then your server does much, much more work in doing lookups to figure out if there's something new.

If you don't like these options, you have to figure out something different, namely something such that when you perform an upload, you somehow notify your other site.
Quote
So I was wondering if the user-stream only snippet is less intrusive for the server because it has to scan a stream only.
*shrug* I doubt there's much in it.
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 22nd, 2012, 07:55 PM
Okay, I changed the code so that after 5 entries it displays the images left as thumbnails instead of standard_resolution. I also added a different text for standard_resolution images and thumbnail ($x_data):

Code: [Select]
<?php
setlocale(LC_TIME'it_IT');
function get_instagram($tag=bombacarta,$count=10,$width=612,$height=612){
$url 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
// Also Perhaps you should cache the results as the instagram API is slow
$cache './wp-content/themes/raymond-31/instagram_json/'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 500){
// 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 style="border-top:1px solid #ddd">'.PHP_EOL;
$ic=0;
foreach ($jsonData->data as $key=>$value) {
$location = (!empty($value->location->name))?'presso '.$value->location->name:null;
if($ic>=5){$width=150;$height=150;$res_c=thumbnail;$x_data="thumbnail text";}else{$res_c=standard_resolution;$x_data="standard resolution text";}
$ic++;
$result .= "\t".'<em>'.htmlentities($value->caption->textENT_QUOTES"UTF-8").'</em><br /><img src="'.$value->images->$res_c->url.'" alt="'.htmlentities($value->caption->textENT_QUOTES"UTF-8").'" width="'.$width.'" height="'.$height.'" /><br /><div class="postinfo">'.$x_data.'</div><br />'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
return $result;
}
echo get_instagram();
?>


The problem is that instead of "standard resolution text" (added as an example), I'd like to add there something like "Scattata da $value->caption->from->full_name". But I don't know how to "include" the $value->caption->from->full_name stuff without errors..

So I tried with:
Code: [Select]
<?php
setlocale(LC_TIME'it_IT');
function get_instagram($tag=bombacarta,$count=10,$width=612,$height=612){
            
$url 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent/?access_token=13137.f59def8.1a759775695548999504c219ce7b2ecf&count='.$count;
            
// Also Perhaps you should cache the results as the instagram API is slow
            
$cache './wp-content/themes/raymond-31/instagram_json/'.sha1($url).'.json';
            if(
file_exists($cache) && filemtime($cache) > time() - 500){
                
// 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 style="border-top:1px solid #ddd">'.PHP_EOL;
            
$ic=0;
            foreach (
$jsonData->data as $key=>$value) {
                
$location = (!empty($value->location->name))?'presso '.$value->location->name:null;
if($ic>=5){$res_c=thumbnail_resolution$x_data="thumb text";}else{$res_c=standard_resolution;$x_data=Scattata da $value->caption->from->full_name 'il' htmlentities(gmstrftime('%e %B %Y alle %R'$value->caption->created_time 7200)) htmlentities($location) }
$ic++;
                
$result .= "\t".'<em>'.htmlentities($value->caption->textENT_QUOTES"UTF-8").'</em><br /><img src="'.$value->images->$res_c->url.'" alt="'.htmlentities($value->caption->textENT_QUOTES"UTF-8").'" width="'.$width.'" height="'.$height.'" /><br /><div class="postinfo">'.$x_data.'</div><br />'.PHP_EOL;
            }
            
$result .= '</div>'.PHP_EOL;
            return 
$result;
        }
echo get_instagram();
?>


But I got a Parse error: syntax error, unexpected T_STRING on line 30, which is:
Code: [Select]
if($ic>=5){$res_c=thumbnail_resolution; $x_data="thumb text";}else{$res_c=standard_resolution;$x_data=Scattata da $value->caption->from->full_name 'il' htmlentities(gmstrftime('%e %B %Y alle %R', $value->caption->created_time + 7200)) htmlentities($location) }
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on April 22nd, 2012, 08:04 PM
Ok, solved. :)
Code: [Select]
$x_data='Scattata da '.$value->caption->from->full_name.' il '.htmlentities(gmstrftime('%e %B %Y alle %R', $value->caption->created_time + 7200)).' '.htmlentities($location);
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on May 3rd, 2012, 04:11 PM
Inexplicable behavior by Internet Explorer. >:( >:( >:(
I have implemented this stuff in 2 websites:
1st: multiformeingegno.it
2nd: bombacarta.com/le-attivita/bombafoto/

Everything works fine in the first website with every browser (including IE), fancybox loads properly and it's ok. In the second website with IE if I click on the thumbnails after the 3 big images, instead of opening Fancybox, IE goes to the thumbnail url!! I can't understand why!! The links are:
<a href="BIG IMAGE URL" class="fancybox" data-fancybox-group="gallery"><img src="THUMB URL" style="margin-right:5px;border:none" alt="" width="150" height="150"/></a>

Everything should work as expected (I have 0 errors on JS console and it is THE SAME FANCYBOX IMPLEMENTATION, SAME FILES AND EVERYTHING)! The thing I can't explain is WHY THE HELL Internet Explorer goes to the thumb URL when the <a> links to the big image!!

Of course everything works properly with ALL other browsers (including Safari Mobile and Android browser)!!!
Title: Re: Extract images with a certain tag from Instagram
Post by: MultiformeIngegno on October 30th, 2012, 08:42 PM
I managed to solve all ths. :)

Anyway another strange thing is happening! :P After some upgrade from PHP 5.4.2 to 5.4.8 (I did every step, so 5.4.2 to 5.4.3, then 5.4.4 to 5.4.5..) - I don't know which upgrade is the "guilty" one :P - the setlocale thing stopped working..

This is my code (I removed the other parts and left the one interesting):
Code: [Select]
<?php
setlocale
(LC_ALL'it_IT');
?>


<div class="box" style="padding-left:20px">
<h2 id="twitter_title">TWITTER</h2>
<?php
$json wp_remote_get("http://api.twitter.com/1/statuses/user_timeline/lorenzoraffio.json?count=9"true);
$decode json_decode($json['body'], true);
echo "
<ul style='color:#6E6E6E'>"
;
$count count($decode); //counting the number of status
for($i=0;$i<$count;$i++){ echo '
<li>'
.$decode[$i]['text'].'<br><a href='; echo '"http://twitter.com/#!/'.$decode[0][user][name].'/status/'.$decode[$i][id].'"><small>'strftime('%e %B',strtotime($decode[$i]['created_at'])) ."</small></a> - <a href='http://twitter.com/intent/tweet?in_reply_to=".$decode[$i][id]."'><small>rispondi</small></a> - <a href='http://twitter.com/intent/retweet?tweet_id=".$decode[$i][id]."'><small>retweet</small></a> - <a href='http://twitter.com/intent/favorite?tweet_id=".$decode[$i][id]."'><small>preferito</small></a></li>";} echo "
</ul>
"
;
?>

</div>

As you can see I set setlocale to it_IT, so strftime('%e %B',strtotime($decode[$i]['created_at'])) should print dates in italian (and it did before upgrading to X PHP version).. for some reason it's in english...