2012-04-14 4 views
2

Je sens que je suis en train de trop réfléchir. Ce que je veux faire est de tirer les photos les plus récentes de l'API instagram et enregistrer les informations JSON qui en résultent dans un fichier cache. J'utiliserai alors jQuery pour lire ce fichier - j'ai compris cette partie. Ce que j'utilise maintenant est de le sauvegarder dans un fichier cache, mais pas dans un format que je reconnais. Je pense que je suis trop compliqué.Utiliser PHP pour stocker json via l'API Instagram

C'est le code que je travaille avec la base d'un tutoriel j'ai trouvé:

// Client ID for Instagram API 
$instagramClientID = '9110e8c268384cb79901a96e3a16f588'; 

$api = 'https://api.instagram.com/v1/media/popular?client_id='.$instagramClientID; //api  request (edit this to reflect tags) 
$cache = 'cache.txt'; 

if(file_exists($cache) && filemtime($cache) > time() - 60*60){ 
// If a cache file exists, and it is newer than 1 hour, use it 
$images = unserialize(file_get_contents($cache)); 
} 
else{ 
// Make an API request and create the cache file 

// For example, gets the 32 most popular images on Instagram 

$response = file_get_contents($api); //change request path to pull different photos 

$images = array(); 

// Decode the response and build an array 
foreach(json_decode($response)->data as $item){ // Decodes json (javascript) into an array 

    $title = ''; 

    if($item->caption){ 
     $title = mb_substr($item->caption->text,0,70,"utf8"); 
    } 

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

    $lat = $item->data->location->latitude; // Caches latitude as $lat 
    $lon = $item->data->location->longtitude; // Caches longitude as $lon  

    $images[] = array(
     "title" => htmlspecialchars($title), 
     "src" => htmlspecialchars($src), 
     "lat" => htmlspecialchars($lat), 
     "lon" => htmlspecialchars($lon) // Consolidates variables to an array 
    ); 
} 

// Remove the last item, so we still have 
// 32 items when when the cover is added 
//array_pop($images); 

// Push the cover in the beginning of the array 
//array_unshift($images,array("title"=>"Cover", "src"=>"assets/img/cover.jpg")); 

// Update the cache file 
file_put_contents($cache,serialize($images)); 
} 
+0

Si vous souhaitez enregistrer le fichier en tant que JSON, utilisez 'json_encode' au lieu de 'sérialiser '. –

+0

@MichaelMior merci. –

Répondre

3

Une chose que je remarqué que l'API est méga lent, bon choix de cache.

Vous essayez d'enregistrer en tant que tableau sérialisé (ce qui n'est pas un gros problème) mais vous pouvez aussi bien le sauvegarder que json si vous le lisez comme json, il économise 1 pas en le désérialisant à nouveau.

Voici quelques modifications que j'ai apportées: Ajout d'une boucle pour essayer d'accélérer la réponse ou de revenir à FGC si vous ne l'avez pas installé. La réponse est enregistrée en tant que json, et lorsqu'elle est extraite du cache, elle est décodée en tant que tableau au lieu d'un objet, ce qui signifie que vous pouvez conserver la même structure de tableau.

$item->data->location->latitude et $item->data->location->longtitude est toujours nulle dans le résultat donc ajouté un chèque que ...

Hope it helps

<?php 
// Client ID for Instagram API 
$instagramClientID = '9110e8c268384cb79901a96e3a16f588'; 

$api = 'https://api.instagram.com/v1/media/popular?client_id='.$instagramClientID; //api request (edit this to reflect tags) 
$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); 
    } 

} 

?> 
+0

Génial! Jouer avec ça maintenant, merci beaucoup. –