T
You can cash all the HTML with pictures. Most likely in the file on the server. A little faster, in operational memory, if there's Memcached, Redis, APC something like that.See if there's a file and if it's fresh. If it's fresh, we'll give it back. Otherwise, we get the data from Instagram, collect the answer, form the HTML, record it in the file and enter the document.It's worth looking at the mistakes - if something went wrong and the answer from Instagram does not contain the expected data? Cashing such a response, or every time and again trying to get data from API, you decide.$insta_tag = 'visitCyprus'; // тег, свой для каждой страны
$key = md5($insta_tag); // ключ для key-value или имя файла
$cache_path = "/tmp"; // папка с кэш-файлами на сервере
$cache_file = sprintf('%s/%s', $cache_path, $key);
$cache_ttl = 900; // время жизни кэша в секундах
$html = ''; // HTML код для вставки на страницу
if( file_exists( $cache_file) && (time() - filemtime($cache_file)) < $cache_ttl) {
// берём кэшированные данные
$html = file_get_contents( $cache_file);
} else {
// надо заново получить данные из Instagram
$client_id = 'xxxxx'; //client_id instagram api
$img_count = 12;
$url = sprintf(
"https://api.instagram.com/v1/tags/%s/media/recent/?%s",
$insta_tag,
http_build_query(array(
"client_id" => $client_id,
"count" => $img_count,
))
);
$response = file_get_contents($url); // запрос к API
$data = json_decode($response, TRUE); // как ассоц. массив
if( is_null( $data) || !isset( $data['data'])) { // плохой ответ от Instagram
$html = "<p>Невозможно получить картинки из Instagram</p>";
} else {
$tmpl = <<<EOFHTML
<a href="%s" target="_blank" class="">
<img src="%s" alt="">
</a>
EOFHTML;
foreach($data['data'] as $img) {
$html .= sprintf(
$tmpl,
$img['link'],
$img['images']['low_resolution']['url']
);
}
file_put_contents( $cache_file, $html);
}
}
echo $html;