php - 使用 PHP 通过 Instagram API 存储 json

标签 php json api instagram

我觉得我想太多了。我想要做的是从 instagram api 中提取最新的照片并将生成的 json 信息保存为缓存文件。然后我将使用 jQuery 来读取该文件——我已经弄清楚了这一部分。我现在使用的是将其保存在缓存文件中,但不是以我识别的格式。我认为我把这个问题过于复杂化了。

这是我根据我找到的教程一直在使用的代码:

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

最佳答案

我注意到的一件事是 API 非常慢,是缓存的好选择。

您正在尝试将其另存为序列化数组(这没什么大不了的),但如果您要再次将其读取为 json,您也可以将其另存为 json,这样可以节省再次反序列化的 1 个步骤。

以下是我所做的一些更改: 添加了curl来尝试加快响应速度,或者如果您没有安装它,则退回到FGC。 响应被保存为 json,当从缓存中检索时,它被解码为数组而不是对象,这意味着您可以保持相同的数组结构。

$item->data->location->latitude$item->data->location->longtitude 在结果中始终为 null,因此添加了检查为此...

希望对你有帮助

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

}

?>

关于php - 使用 PHP 通过 Instagram API 存储 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10157221/

相关文章:

php - 基本页脚定位问题

php - 使用 php 将远程 img 文件保存到服务器

javascript - 从 JSON 文件返回 RegExp 模式以创建 Angular 指令

python - 合并两个 YouTube API 脚本

php - 如果从另一个表连接时记录中包含重复项,则显示记录中的一个名称

javascript - 想要生成带有猫头鹰图像的轮播

java - 将 XML 转换为 JSON 忽略属性

java - Jackson 和 GSON 中 JSON 对象的稳定/术语比较

python - 对 Telegram.org "Error 500: RPC_SEND_FAIL"的正确回应

api - 环回连接器 REST API