簡體   English   中英

我怎樣才能獲得json文件的一部分而不是整個PHP的部分?

[英]How can I get only a part of a json file instead of the entire thing with php?

我正在連接到trakt.tv api,我想為自己創建一個小應用程序,顯示評級等電影海報。

這就是我目前用來檢索包含我需要的所有信息的.json文件。

$json = file_get_contents('http://api.trakt.tv/movies/trending.json/2998fbac88fd207cc762b1cfad8e34e6');
$movies = json_decode($json, true);

$movies = array_slice($movies, 0, 20);

foreach($movies as $movie) {
    echo $movie['images']['fanart'];
}

因為.json文件很大,所以加載速度很慢。 我只需要文件中的幾個屬性,如標題,評級和海報鏈接。 除此之外,我只需要前20個左右。 我怎樣才能確保只加載.json文件的一部分來加載它?

除此之外,我沒有經驗與php結合.json,所以如果我的代碼是垃圾,你有建議,我很樂意聽到他們。

除非API提供limit參數或類似參數,否則我認為您不能限制查詢。 快速查看它似乎沒有提供這個。 它也看起來不像真的返回那么多數據(100KB以下),所以我猜它只是很慢。

鑒於API速度慢,我會緩存您收到的數據,並且每小時左右只更新一次。 您可以使用file_put_contents將其保存到服務器上的文件中,並記錄它的保存時間。 當您需要使用數據時,如果保存的數據超過一個小時,請刷新它。

這個想法的快速草圖有效:

function get_trending_movies() {
    if(! file_exists('trending-cache.php')) {
        return cache_trending_movies();
    }

    include('trending-cache.php');
    if(time() - $movies['retreived-timestamp'] > 60 * 60) { // 60*60 = 1 hour
        return cache_trending_movies();
    } else {
        unset($movies['retreived-timestamp']);
        return $movies;
    }
}

function cache_trending_movies() {
    $json = file_get_contents('http://api.trakt.tv/movies/trending.json/2998fbac88fd207cc762b1cfad8e34e6');
    $movies = json_decode($json, true);
    $movies = array_slice($movies, 0, 20);
    $movies_with_date = $movies;
    $movies_with_date['retreived-timestamp'] = time();
    file_put_contents('trending-cache.php', '<?php $movies = ' . var_export($movies_with_date, true) . ';');
    return $movies;
}

print_r(get_trending_movies());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM