30

I need to get some pictures which have a specific hashtag using PHP ? Any help will be awesome, or hint ?

Sosian
  • 622
  • 11
  • 28
Zeid Selimovic
  • 843
  • 3
  • 13
  • 19

6 Answers6

26

Here's another example I wrote a while ago:

<?php       
    // Get class for Instagram
    // More examples here: https://github.com/cosenary/Instagram-PHP-API
    require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('CLIENT_ID_HERE');

    // Set keyword for #hashtag
    $tag = 'KEYWORD HERE';

    // Get latest photos according to #hashtag keyword
    $media = $instagram->getTagMedia($tag);

    // Set number of photos to show
    $limit = 5;

    // Set height and width for photos
    $size = '100';

    // Show results
    // Using for loop will cause error if there are less photos than the limit
    foreach(array_slice($media->data, 0, $limit) as $data)
    {
        // Show photo
        echo '<p><img src="'.$data->images->thumbnail->url.'" height="'.$size.'" width="'.$size.'" alt="SOME TEXT HERE"></p>';
    }
?>
kexxcream
  • 5,873
  • 8
  • 43
  • 62
  • Do you know of any way to get past the limit of 20? – Staysee May 14 '13 at 15:28
  • @Staysee See answer below. – kexxcream May 20 '13 at 13:52
  • 1
    @kexxcream I'm running your API and I want to getTagMedia for the hashtag #thesouthfarm. Problem is that I only get my own images with that tag. Not my friends. Is there some limitations there? – Ismailp Jun 20 '13 at 18:04
  • @Ismailp It's not my API, it's just a wrapper. There shouldn't be any limitations as long as you enter correct client id and keyword for hashtag. How does your code look? – kexxcream Jun 21 '13 at 05:42
  • 1
    @kexxcream sorry for that! Found out that the users had private profiles and thus I could not fetch teh photos! :) – Ismailp Jun 22 '13 at 12:18
  • 1
    With the latest version of the Instagram-PHP-API wrapper you need to pass the limit to the getTagMedia() method: `$instagram->getTagMedia($tag, 5);` and then replace the foreach line with `foreach($media->data as $data) {`. (Also, the easiet way to load the wrapper is now by using [Composer](https://getcomposer.org/) - see examples on wrapper's Github page) – TheStoryCoder May 29 '16 at 08:11
  • how to do this in an android app? – Hammad Nasir Aug 26 '17 at 05:26
22

There is the instagram public API's tags section that can help you do this.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
  • The first URL seems broken. This one works: http://instagram.com/developer/endpoints/tags/ – Shahar Feb 19 '14 at 21:48
  • 1
    The instagram API just appears *insane*. Do they really expect you to obtain authentication from every visitor just to get a public feed? – Simon East Oct 21 '14 at 00:07
  • You dont need to authenticate users for such requests. You client id will suffice. Your app will need user authentication if it does something on behalf of user. (commenting, liking, browsing a user’s feed, etc.). – Sinan Dec 04 '14 at 23:20
  • @SimonEast the intention is that you don't use the API for these purposes at all. They want you feeding into the ecosystem, not pulling content out of it. – Nathan Hornby Mar 10 '17 at 09:44
  • Is there any way to get the posts using various hashtags in my android app? – Hammad Nasir Aug 26 '17 at 05:25
16

If you only need to display the images base on a tag, then there is not to include the wrapper class "instagram.class.php". As the Media & Tag Endpoints in Instagram API do not require authentication. You can use the following curl based function to retrieve results based on your tag.

 function callInstagram($url)
    {
    $ch = curl_init();
    curl_setopt_array($ch, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => 2
    ));

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
    }

    $tag = 'YOUR_TAG_HERE';
    $client_id = "YOUR_CLIENT_ID";
    $url = 'https://api.instagram.com/v1/tags/'.$tag.'/media/recent?client_id='.$client_id;

    $inst_stream = callInstagram($url);
    $results = json_decode($inst_stream, true);

    //Now parse through the $results array to display your results... 
    foreach($results['data'] as $item){
        $image_link = $item['images']['low_resolution']['url'];
        echo '<img src="'.$image_link.'" />';
    }
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
Gursharan Singh
  • 364
  • 6
  • 19
  • I've noticed it grabs only 20 pictures. Are those 20 latest pictures? How to get more? – dKab Oct 22 '14 at 18:10
  • Those are the latest 20. If you look at the URL, it has 'media/recent'. According to the Instagram API, that will order by datetime descending. – mirichan Oct 24 '14 at 08:12
  • @Gursharan Singh Hello i have hashtag with underscore and i'm using this code and work fine for all hashtag except hashtag with underscore any help. – Fadi Jan 03 '16 at 09:32
  • but do you really see all picutres? Im in sandbox mode, i can only see the pictures of the accesstoken-owner? – BvuRVKyUVlViVIc7 Jan 05 '16 at 11:30
  • How can I get posts from Instagram in my android app using various hashtags? – Hammad Nasir Aug 28 '17 at 06:43
14

Since Nov 17, 2015 you have to authenticate users to make any (even such as "get some pictures who have specific hashtag") requests. See the Instagram Platform Changelog:

Apps created on or after Nov 17, 2015: All API endpoints require a valid access_token. Apps created before Nov 17, 2015: Unaffected by new API behavior until June 1, 2016.

this makes now all answers given here before June 1, 2016 no longer useful.

Szymon Jeż
  • 8,273
  • 4
  • 42
  • 60
  • but you can get "get some pictures who have specific hashtag" [without the need of an API](http://stackoverflow.com/questions/40542335/how-to-get-all-images-of-hashtag-in-instagram-without-api) – machineaddict Nov 21 '16 at 12:57
  • 2017 and i still can get data without access token. Example: https://www.instagram.com/salvun/media/ – redochka Aug 07 '17 at 09:37
  • how can I get posts using various hashtags in my android app? – Hammad Nasir Aug 26 '17 at 05:25
8

I have set a php code which can help in case you want to access Instagram images without api on basis of hashtag

Php Code for Instagram hashtag images

AHSAN KHAN
  • 426
  • 7
  • 17
5

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}
kexxcream
  • 5,873
  • 8
  • 43
  • 62
  • This works great! +1 If oy uhave time, could you look at a similar problem that I have? http://stackoverflow.com/questions/17487231/input-value-in-ajax-call-does-not-work – Bram Vanroy Jul 05 '13 at 10:56
  • It seems someone else managed to answer faster so I guess it's solved. – kexxcream Jul 05 '13 at 14:07
  • Yes, apparently. Thanks anyway! – Bram Vanroy Jul 06 '13 at 15:31
  • EXACTLY what I was searching for ! Thanks Kexxcream. One problem remaining. The number of pictures displayed change all the time from 13 pictures to 18. How to fix that? And btw, it's strange, the picture size are not the same. Sometimes I see non square images ! But good script! Love it! Thanks kexxcream – jhon Aug 01 '13 at 23:00
  • 1
    No need to hack the core. Instead of editing instagram.class.php just set `$instagram->setClientID('YOUR_CLIENT_ID');` – The Silencer Mar 09 '14 at 13:23
  • doesnt work anymore, access_token is also needed. – BvuRVKyUVlViVIc7 Jan 05 '16 at 11:30