使用PHP获取所有带有特定标签的Instagram照片

30

我需要使用PHP获取一些具有特定标签的图片?

任何帮助都会很棒,或者有什么提示吗?

6个回答

26

这是我之前写的另一个示例:

<?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>';
    }
?>

你知道有什么方法可以突破20的限制吗? - Staysee
1
@kexxcream 我正在运行你的API,想要获取标签 #thesouthfarm 的 getTagMedia。问题是我只能得到自己的带有该标签的图片,而无法获取我的朋友们的。这里是否存在某些限制? - Ismailp
@Ismailp 这不是我的API,它只是一个包装器。只要您输入正确的客户端ID和哈希标签的关键字,就不应该有任何限制。您的代码是怎么样的? - kexxcream
1
@kexxcream 很抱歉!发现这些用户的个人资料是私密的,因此我无法获取照片! :) - Ismailp
1
通过最新版本的Instagram-PHP-API包装器,您需要将限制传递给getTagMedia()方法:$instagram->getTagMedia($tag, 5);,然后用foreach($media->data as $data) {替换foreach行。 (此外,现在使用[Composer](https://getcomposer.org/)加载包装器的最简单方法-请参阅包装器的Github页面上的示例) - TheStoryCoder
显示剩余2条评论

22

有 Instagram 公共 API 的标签部分可以帮助您完成此操作。


第一个网址似乎失效了。这个可以使用:http://instagram.com/developer/endpoints/tags/ - Shahar
@Shahar 更新中,谢谢。 - Anirudh Ramanathan
1
Instagram API 看起来疯狂。他们真的希望你从每个访问者那里获取认证才能获得公共信息流吗? - Simon East
您不需要为此类请求进行用户身份验证。您的客户端ID就足够了。如果您的应用程序代表用户执行某些操作(例如评论、点赞、浏览用户的动态等),则需要进行用户身份验证。 - Sinan
@SimonEast 的意图是你根本不应该将 API 用于这些目的。他们希望你为生态系统提供支持,而不是从中获取内容。 - Nathan Hornby
有没有办法在我的Android应用程序中使用各种标签获取帖子? - Hammad Nasir

16

如果你只需要根据标签展示图片,那么不需要包含 "instagram.class.php" 包装类。由于 Instagram API 中的媒体和标签终端点不需要身份验证,因此您可以使用以下基于curl的函数来检索基于标签的结果。

 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.'" />';
    }

我注意到它只获取了20张图片。那20张是最新的吗?如何获取更多? - dKab
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - mirichan
@Gursharan Singh 你好,我有一个带下划线的hashtag,并且我正在使用这段代码,对于除了带下划线的hashtag之外的所有hashtag都可以正常工作,请帮忙解决一下。 - Fadi
但是你真的能看到所有的图片吗?我处于沙盒模式,只能看到访问令牌所有者的图片。 - BvuRVKyUVlViVIc7
如何在我的安卓应用中使用不同的标签获取Instagram上的帖子? - Hammad Nasir

14
自2015年11月17日起,您必须对用户进行身份验证才能进行任何请求(即使是“获取带有特定标签的某些图片”)。请参见Instagram平台更改日志

在2015年11月17日或之后创建的应用程序: 所有API端点都需要有效的access_token。 在2015年11月17日之前创建的应用程序: 直到2016年6月1日不受新API行为影响。

这意味着在2016年6月1日之前给出的所有答案现在都已失效。

但是你可以获取“具有特定标签的一些图片”[无需API](https://dev59.com/MFkR5IYBdhLWcg3w_B_-) - machineaddict
2017 年了,我仍然可以在没有访问令牌的情况下获取数据。例如:https://www.instagram.com/salvun/media/ - redochka
我该如何在我的安卓应用中使用不同的标签获取帖子? - Hammad Nasir

8

太棒了!这正是我所需要的。 - Maxim Mazurok
1
刚刚创建了一个Gist,其中包含用NodeJS(ES6)重写的代码:https://gist.github.com/Maxim-Mazurok/404755f94091ab748f257309779c134b - Maxim Mazurok
这是很棒的工作 @MaximMazurok - AHSAN KHAN

5

如果需要显示超过20个内容,您可以使用“加载更多”按钮。

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

找到函数getTagMedia()并替换为:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

这个很好!+1 如果你有时间,能否看一下我遇到的类似问题?http://stackoverflow.com/questions/17487231/input-value-in-ajax-call-does-not-work - Bram Vanroy
好像有人回答得更快,所以我想问题已经解决了。 - kexxcream
是的,显然。无论如何感谢你! - Bram Vanroy
正是我一直在寻找的!谢谢Kexxcream。还有一个问题没有解决。显示的图片数量总是从13张变成18张。如何解决?顺便说一下,很奇怪,图片大小不一样。有时我看到的是非方形图像!但是好脚本!喜欢它!谢谢Kexxcream - jhon
1
不需要修改核心代码。只需设置$instagram->setClientID('YOUR_CLIENT_ID');,而不是编辑instagram.class.php文件。 - The Silencer
不再起作用了,还需要 access_token。 - BvuRVKyUVlViVIc7

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接