2012-04-14 53 views
2

私はこれを思っているように感じます。私がやりたいことは、最新の写真をInstagram APIから取り出して、結果のjson情報をキャッシュファイルとして保存することです。私はそのファイルからjQueryを使って読み込みます - 私はその部分を理解しました。私が今使っているのは、それをキャッシュファイルに保存することですが、私が認識するフォーマットではありません。私はこれを過度に複雑にしていると思う。PHPを使ってInstagram API経由でjsonを保存する

これは私が私が見つけたのチュートリアルをもとにして取り組んできたコードです:私が気づい

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

を役に立てば幸い結果は常にNULLです'シリアライズ'の。 –

+0

@MichaelMiorありがとう。 –

答えて

3

一つは、APIがキャッシュにメガ遅い、良い選択です。

シリアライズされた配列(大したことはありません)として保存しようとしていますが、jsonとしてもう一度読むとjsonと同じように保存することもできます。

ここにいくつかの変更があります: 応答を高速化しようとするカールを追加しました。インストールしていない場合は、FGCにフォールバックしてください。 レスポンスはjsonとして保存され、オブジェクトからではなく配列としてデコードされたキャッシュから取得すると、同じ配列構造を保持できます。

$item->data->location->latitude$item->data->location->longtitudeので、そのためのチェックを追加しました...あなたはJSONとしてファイルを保存したい場合は

が代わりに `json_encode`使用し、それは

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

恐ろしい!これで今遊んで、ありがとう。 –

関連する問題