Nano Hash - криптовалюты, майнинг, программирование

Кэширование запросов API Instagram с использованием PHP?

Вот мой текущий скрипт, который выполняет вызов API:

 $client = "55447265ed444bb5b768ecb0765ba9cb";  
 $query = $_POST['q'];  
 $clnum = mt_rand(1,3);

 $api = "https://api.instagram.com/v1/tags/".$query."/media/recent?client_id=".$client;  

 function get_curl($url) {
 if(function_exists('curl_init')) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    $output = curl_exec($ch);
    echo curl_error($ch);
    curl_close($ch);
    return $output;
} else{
    return file_get_contents($url);
}
 }

 $response = get_curl($api);
 $images = array();

 if($response){
foreach(json_decode($response)->data as $item){     
    $src = $item->images->standard_resolution->url;
    $thumb = $item->images->thumbnail->url;
    $url = $item->link;

    $images[] = array(
    "src" => htmlspecialchars($src),
    "thumb" => htmlspecialchars($thumb),
    "url" => htmlspecialchars($url)
    );

}
 }

 print_r(str_replace('\\/', '/', json_encode($images)));
 die();

Я нашел 2 кода, которые могут кэшировать, но мне нужна помощь, чтобы интегрировать их в мой текущий скрипт. Один сценарий длиннее другого. Оба сценария делают переменную $cache, за которой следует код «если, иначе», после чего они оба разветвляются на разные коды. Второй код действительно похож на мой текущий скрипт, но я пытаюсь понять, как их объединить.

1-й код:

// 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));
}

$result = '<div id="instagram">'.PHP_EOL;
foreach ($jsonData->data as $key=>$value) {
    $result .= "\t".'<a class="fancybox" data-fancybox-group="gallery" 
                        title="'.htmlentities($value->caption->text).' '.htmlentities(date("F j, Y, g:i a", $value->caption->created_time)).'"
                        style="padding:3px" href="'.$value->images->standard_resolution->url.'">
                      <img src="'.$value->images->low_resolution->url.'" alt="'.$value->caption->text.'" width="'.$width.'" height="'.$height.'" />
                      </a>'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
return $result;
}

2-й код:

 $cache = './cache.json';

 if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$images = json_decode(file_get_contents($cache),true); //Decode as an json array
 }
   else{
  // Make an API request and create the cache file
 // For example, gets the 32 most popular images on Instagram
  $response = get_curl($api); //change request path to pull different photos

  $images = array();

if($response){
    // Decode the response and build an array
    foreach(json_decode($response)->data as $item){

        $title = (isset($item->caption))?mb_substr($item->caption->text,0,70,"utf8"):null;

        $src = $item->images->standard_resolution->url; //Caches standard res img path to variable $src

        //Location coords seemed empty in the results but you would need to check them as mostly be undefined
        $lat = (isset($item->data->location->latitude))?$item->data->location->latitude:null; // Caches latitude as $lat
        $lon = (isset($item->data->location->longtitude))?$item->data->location->longtitude:null; // Caches longitude as $lon

        $images[] = array(
        "title" => htmlspecialchars($title),
        "src" => htmlspecialchars($src),
        "lat" => htmlspecialchars($lat),
        "lon" => htmlspecialchars($lon) // Consolidates variables to an array
        );
    }
    file_put_contents($cache,json_encode($images)); //Save as json
}
 }

 //Debug out
 print_r($images);

 //Added curl for faster response
 function get_curl($url){
if(function_exists('curl_init')){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    $output = curl_exec($ch);
    echo curl_error($ch);
    curl_close($ch);
    return $output;
}else{
    return file_get_contents($url);
}

 }
13.12.2013

  • @kwollaston - К сожалению, не знаю, как поместить ETag в код. Я просто смотрю на свой код и 2 других кода. 13.12.2013

Ответы:


1

Я использовал приведенный ниже код, который взят из предоставленного вами кода, и, похоже, он работает нормально.

<?php    
$client = "55447265ed444bb5b768ecb0765ba9cb";  
$query = $_POST['q'];  
$clnum = mt_rand(1,3);

$api = "https://api.instagram.com/v1/tags/".$query."/media/recent?client_id=".$client;  

function get_curl($url) {
    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
        $output = curl_exec($ch);
        echo curl_error($ch);
        curl_close($ch);
        return $output;
    } else{
        return file_get_contents($url);
    }
}

$images = array();

$cache = './cache.json';

if(file_exists($cache) && filemtime($cache) > time() - 60*60){
    // If a cache file exists, and it is newer than 1 hour, use it
    $images = json_decode(file_get_contents($cache),true); //Decode as an json array
} else {
    // Make an API request and create the cache file
    // For example, gets the 32 most popular images on Instagram
    $response = get_curl($api); //change request path to pull different photos

    $images = array();

    if($response){
        // Decode the response and build an array
        foreach(json_decode($response)->data as $item){

            $title = (isset($item->caption))?mb_substr($item->caption->text,0,70,"utf8"):null;

            $src = $item->images->standard_resolution->url; //Caches standard res img path to variable $src

            //Location coords seemed empty in the results but you would need to check them as mostly be undefined
            $lat = (isset($item->data->location->latitude))?$item->data->location->latitude:null; // Caches latitude as $lat
            $lon = (isset($item->data->location->longtitude))?$item->data->location->longtitude:null; // Caches longitude as $lon

            $images[] = array(
                "title" => htmlspecialchars($title),
                "src" => htmlspecialchars($src),
                "lat" => htmlspecialchars($lat),
                "lon" => htmlspecialchars($lon) // Consolidates variables to an array
            );        
            file_put_contents($cache,json_encode($images)); //Save as json
        }
    }    
 }

//Debug out
echo "<pre>";
print_r($images);
10.01.2014

2

Да, это работает. Но вам нужно использовать функцию кеша, потому что API Instagram очень медленный. Неважно, используете ли вы curl или file_get_contents... самый быстрый способ - это jquery. Jquery использует клиентскую машину php на сервере.. и если сервер стоит в стороне от серверов API, это требует времени.

17.07.2017
Новые материалы

Кластеризация: более глубокий взгляд
Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

Как написать эффективное резюме
Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

Частный метод Python: улучшение инкапсуляции и безопасности
Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

Как я автоматизирую тестирование с помощью Jest
Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

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

Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..