Как получить пользовательский канал в Instagram - PullRequest
15 голосов
/ 10 июня 2011

Я бы хотел получить пользовательский фид в Instagram, используя PHP.Я подписался на учетную запись разработчика Instagram и попытался добавить информацию и фотографии пользователя, но ответ не стабилен.Иногда я получаю ответ, а иногда я получаю сообщение об ошибке: отсутствует access_token.Есть ли надежный пример получения пользовательского фида фотографий по имени пользователя?

В идеале мне бы хотелось, чтобы это было так просто:

$instagram = new Instagram();
$photos = $instagram->getPhotos("username-goes-here");

Где Instagram - это класс, который обрабатываетвсе запросы.Любая помощь или направление приветствуется.Спасибо!

Ответы [ 6 ]

56 голосов
/ 10 июля 2012

Попробуйте это,

<?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/ID-GOES-HERE/media/recent/?access_token=TOKEN-GOES-HERE");
  $result = json_decode($result);
  foreach ($result->data as $post) {
    // Do something with this data.
  }
?>

Да поможет вам это.

6 голосов
/ 23 августа 2013

Я сделал это:

<?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");


  $result = json_decode($result);
  foreach ($result->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>';
     }

  }
?>
4 голосов
/ 30 августа 2014

Взяв то, что я видел в интернете и на этой странице, я создал класс Instagram (очень простой, только для извлечения каналов и т. Д.) Ниже.

class Instagram {
    public static $result;
    public static $display_size = 'thumbnail'; // you can choose between "low_resolution", "thumbnail" and "standard_resolution"
    public static $access_token = "DEFAULTACCESSTOKEN"; // default access token, optional
    public static $count = 10;
    public static function fetch($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;
    }
    function __construct($Token=null){
        if(!empty($Token)){
            self::$access_token = $Token;

            // Remove from memory -- not sure if really needed.
            $Token = null;
            unset($Token);
        }
        self::$result = json_decode(self::fetch("https://api.instagram.com/v1/users/self/media/recent?count=" . self::$count . "&access_token=" . self::$access_token), true);
    }
}
$Instagram = new Instagram('ACCESSTOKENIFCHANGEDORNULLOREMPTY');
foreach ($Instagram::$result->data as $photo) {
    $img = $photo->images->{$Instagram::$display_size};
}
1 голос
/ 04 июня 2016

Обновление: 15.6.2017 - Instagram изменил конечную точку, следующее больше не работает.

Поскольку больше невозможно получить фид случайных пользователей без утвержденного приложения, яВыяснили, как получить его с помощью неофициального API:

#!/bin/bash
instagram_user_id=25025320
count=12
csrftoken=$(curl --head -k https://www.instagram.com/ 2>&1 | grep -Po "^Set-Cookie: csrftoken=\K(.*?)(?=;)")
curl "https://www.instagram.com/query/" -H "cookie: csrftoken=$csrftoken;" -H "x-csrftoken: $csrftoken" -H "referer: https://www.instagram.com/" --data "q=ig_user($instagram_user_id)%20%7B%20media.after(0%2C%20$count)%20%7B%0A%20%20count%2C%0A%20%20nodes%20%7B%0A%20%20%20%20caption%2C%0A%20%20%20%20code%2C%0A%20%20%20%20comments%20%7B%0A%20%20%20%20%20%20count%0A%20%20%20%20%7D%2C%0A%20%20%20%20date%2C%0A%20%20%20%20dimensions%20%7B%0A%20%20%20%20%20%20height%2C%0A%20%20%20%20%20%20width%0A%20%20%20%20%7D%2C%0A%20%20%20%20display_src%2C%0A%20%20%20%20id%2C%0A%20%20%20%20is_video%2C%0A%20%20%20%20likes%20%7B%0A%20%20%20%20%20%20count%0A%20%20%20%20%7D%2C%0A%20%20%20%20owner%20%7B%0A%20%20%20%20%20%20id%2C%0A%20%20%20%20%20%20username%2C%0A%20%20%20%20%20%20full_name%2C%0A%20%20%20%20%20%20profile_pic_url%0A%20%20%20%20%7D%2C%0A%20%20%20%20thumbnail_src%2C%0A%20%20%20%20video_views%0A%20%20%7D%2C%0A%20%20page_info%0A%7D%0A%20%7D" -k

Я улучшу этот ответ позже с помощью PHP, мне нужно сделать это и с PHP.

0 голосов
/ 08 июня 2019

Найден этот средний артикул: - https://medium.com/@bkwebster/how-to-get-instagram-api-access-token-and-fix-your-broken-feed-c8ad470e3f02

 <?php
                    $user_id=xxxxxx;//User ID is the first string of numbers before the first dot (.)
                    $count=2;
                    $width=100;
                    $height=100;
                    $url = 'https://api.instagram.com/v1/users/'.$user_id.'/media/recent/?access_token=xxxxxx.83c3b89.257e2fd9c2bd40c181a2a4fb9576628c&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));
                    }
                    foreach ($jsonData->data as $key=>$value) {
                        ?>
                        <ul class="w3_footer_grid_list1">
                            <li><label class="fa fa-instagram" aria-hidden="true"></label><a target="_blank" href="<?php echo $value->link;?>"><i><?php echo $value->caption->text; ?> </i></a><?php  ?>
                            </li>
                            <a target="_blank" href="<?php echo $value->link;?>">
                            <img src="<?php echo  $value->images->low_resolution->url;?>" alt="'.$value->caption->text.'" width="<?php echo $width;?>" height="<?php echo $height;?>" />
                            </a>
                        </ul>
                        <?php
                    }
                ?>
0 голосов
/ 21 сентября 2016

Попробуйте этот тип сканера в необработанном виде.

function feed_instagram($url = "https://www.instagram.com/titaniumheart_")
{  
    //$url ie https://www.instagram.com/titaniumheart_

    $dom = new DOMDocument();
    @$dom->loadHTMLFile($url);
    $f=$dom->saveHTML();  //load the url (crawl)

    $key="";    
    $swquote=0;     
    echo "<div>";

    for ($x=0;$x<strlen($f);$x++)
    {
       $c=substr($f,$x,1);
       //echo $c."-";
        if ($c==chr(34)) 
        {
            if($swquote==0)
            {
                $swquote=1; //to start get chars
            } else
            {
                $swquote=0;
                //echo $key;
                if($key=="code")
                {
                    //get the number of comments
                    $m=substr($f,$x+4,100);
                    $code= substr($m,0,strpos($m,chr(34)));
                    echo "code is ".$code;
                    echo "<br>";
                }               
                if($key=="comments")
                {
                    //get the number of comments
                    $m=substr($f,$x+12,20);
                    $comments= substr($m,0,strpos($m,"}"));
                    echo "number of comments is ".$comments;
                    echo "<br>";
                }
                if($key=="caption")
                {
                    //get the number of comments
                    $m=substr($f,$x+4,200);
                    $caption= substr($m,0,strpos($m,chr(34)));
                    echo "caption is ".$caption;
                    echo "<br>";
                }
                if($key=="likes")
                {
                    //get the number of comments
                    $m=substr($f,$x+12,20);
                    $likes= substr($m,0,strpos($m,"}"));
                    echo "number of likes is ".$likes;
                    echo "<br>";
                }
                if($key=="thumbnail_src")
                {
                    //get the number of comments
                    $m=substr($f,$x+4,200);
                    $src= substr($m,0,strpos($m,"?"));
                    echo "<br>image source is ".$src;
                    echo "<br>";                                    
                    echo "<a href=\"https://www.instagram.com/p/".$code."/\">";
                    echo "<img src=\"".$src."\">";
                    echo "</a><br>";                    
                }                               
               $key="";
        }

    }else
    {
        if($swquote==1)
        {
            $key.=$c;
        }
    }           
}
echo "</div>";
}

использование: https://www.instagram.com/titaniumheart_");?>

обратите внимание: вы должны включить расширение "php_openssl" в php.ini.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...