简体   繁体   English

使用PHP缓存Instagram API请求?

[英]Caching Instagram API requests using PHP?

Here's my current script that does the API calling: 这是我当前执行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();

I found 2 codes that can do caching but need help integrating them into my current script. 我发现了2个可以进行缓存的代码,但是需要帮助将它们集成到当前脚本中。 One script is longer than the other. 一个脚本比另一个脚本长。 Both scripts do a $cache variable followed by an "if, else" code then they both branch out into different codes. 这两个脚本都执行$ cache变量,后跟“ if,else”代码,然后它们都分支为不同的代码。 The 2nd code is really similar to my current script but trying to figure out how to merge them. 第二个代码确实类似于我当前的脚本,但是试图弄清楚如何合并它们。

1st code: 第一个代码:

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

2nd code: 第二个代码:

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

 }

I used below code which is taken from your provided code and it seems to be working fine.. 我使用了下面的代码,这些代码取自您提供的代码,并且似乎工作正常。

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

Yeah this works. 是的,这有效。 But u need to use the cache function because the instagram api is really slow. 但是您需要使用缓存功能,因为instagram api确实很慢。 It doesn't matter if u take curl or file_get_contents.... the fastes way is jquery. 您是否使用curl或file_get_contents都没有关系。...快车方式是jquery。 Jquery uses the client machine php the server.. and if ure server stands away from the api servers so it takes time. jQuery使用客户端计算机php服务器..如果ure服务器远离api服务器,则需要花费时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM