我怎么能只获取 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());