2013-08-24 2 views
1

Я использую приведенный ниже код, который хорошо работает при загрузке всех изображений, соответствующих тегу #spproject. То, что я хотел бы сделать, - загрузить 9 фотографий за один раз, а затем либо загрузить больше с помощью ajax, либо просто ссылку на предыдущие/следующие страницы. Проблема в том, что я не совсем понимаю, как это сделать с помощью API, можете ли вы помочь?Отображение API-схемы Instagram

КОД:

<?PHP 
function get_instagram($next=null,$width=160,$height=160){ 

    if($next == null) { 
     $url = 'https://api.instagram.com/v1/tags/spproject/media/recent?access_token=[TOKEN]&count=10'; 
    } 
    else { 
     $url .= '&max_tag_id=' . $next; 
    } 

    //Also Perhaps you should cache the results as the instagram API is slow 
    $cache = './'.sha1($url).'.json'; 
    //unlink($cache); // Clear the cache file if needed 

    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 id="instagramPhotos">'.PHP_EOL; 
    if (is_array($jsonData->data)) 
    { 
     foreach ($jsonData->data as $key=>$value) 
     { 
      $result .= '<li><div class="album"> 
     <figure class="frame"> 
      <a href="'.$value->link.'" target="_blank"><i><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'"></i></a> 
     </figure> 
     <span class="count">#SPproject</span> 
     <a href="http://www.instagram.com/'.$value->user->username.'" target="_blank"><figcaption class="name">'.$value->user->username.'</figcaption></a> 
    </div></li>'.PHP_EOL; 
     } 
    } 
    $result .= '</ul>'.PHP_EOL; 

    if(isset($jsonData->pagination->next_max_tag_id)) { 
     $result .= '<div><a href="?next=' . $jsonData->pagination->next_max_tag_id . '">Next</a></div>'; 
    } 

    return $result; 
} 
?> 
<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>#SPproject - A worldwide instagram idea</title> 
    <link rel="stylesheet" href="style.css"> 
    <link rel="stylesheet" href="normalize.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script> 
     $(document).ready(function(){ 
      var totalPhotos = $('#instagramPhotos > li').size(); 
      $('#result').text('Total tagged images: '+totalPhotos); 
     }); 
    </script> 
</head> 
<body> 
    <div id="container"> 
     <?=get_instagram(@$_GET['next']);?> 

     <div id="result"></div> 
    </div> 
</body> 
</html> 

сайт: http://www.spproject.info/

ответ

3

объект JSON, который Instagram возвращается содержит переменную постраничной и, в свою очередь, в "next_url" переменной. next_url - это URL-адрес API, который необходимо вызвать для получения следующей страницы результатов.

Here is a good tutorial на разбивке на страницы с Instagram. Кроме того, совет для будущего - не публикуйте свои коды доступа к API в Интернете ...

Код (пересмотренный) ниже должен быть хорошей отправной точкой для вас.

<?PHP 
function get_instagram($next=null,$width=160,$height=160){ 

    $url = 'https://api.instagram.com/v1/tags/spproject/media/recent?access_token=[token]&count=9'; 

    if($url !== null) { 
     $url .= '&max_tag_id=' . $next; 
    } 

    //Also Perhaps you should cache the results as the instagram API is slow 
    $cache = './'.sha1($url).'.json'; 
    //unlink($cache); // Clear the cache file if needed 

    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 id="instagramPhotos">'.PHP_EOL; 
    foreach ($jsonData->data as $key=>$value) { 
     $result .= '<li><div class="album"> 
     <figure class="frame"> 
      <a href="'.$value->link.'" target="_blank"><i><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'"></i></a> 
     </figure> 
     <span class="count">#SPproject</span> 
     <a href="http://www.instagram.com/'.$value->user->username.'" target="_blank"><figcaption class="name">'.$value->user->username.'</figcaption></a> 
    </div></li>'.PHP_EOL;; 
     //$result .= '<li><a href="'.$value->link.'"><img src="'.$value->images->standard_resolution->url.'" alt="" width="'.$width.'" height="'.$height.'" name="'.$value->user->username.'" /></a></li>'.PHP_EOL; 
    } 
    $result .= '</ul>'.PHP_EOL; 

    if(isset($jsonData->pagination->next_max_tag_id)) { 
     $result .= '<div><a href="?next=' . $jsonData->pagination->next_max_tag_id . '">Next</a></div>'; 
    } 

    return $result; 
} 
?> 
<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>#SPproject - A worldwide instagram idea</title> 
    <link rel="stylesheet" href="style.css"> 
    <link rel="stylesheet" href="normalize.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script> 
     $(document).ready(function(){ 
      var totalPhotos = $('#instagramPhotos > li').size(); 
      $('#result').text('Total tagged images: '+totalPhotos); 
     }); 
    </script> 
</head> 
<body> 
    <div id="container"> 
     <?=get_instagram(@$_GET['next']);?> 

     <div id="result"></div> 
    </div> 
</body> 
</html> 
+0

Хороший крик о коде доступа, полностью соскользнул с ума. Удалил это сейчас :) Спасибо за это. Когда я запускаю код, он показывает 9 штрафа, однако, когда я нажимаю дальше, он не обновляет фотографии: (вот что показано в адресной строке: http: // localhost: 8888/spproject /? Url = https: //api.instagram.com/v1/tags/spproject/media/recent?access_token=TOKEN&count=10&max_tag_id=1375226444984 –

+0

Ah - было бы неплохо заменить '$ jsonData-> pagination-> next_url' на' urlencode ($ jsonData-> pagination-> next_url) 'и' get_instagram (160,160, $ _ GET ['url']) 'с' get_instagram (160,160, urlencode ($ _ GET ['url'])) ' – Aidan

+0

2 секунды, просто попробуйте –

Смежные вопросы