简体   繁体   English

我怎样才能获得json文件的一部分而不是整个PHP的部分?

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

I'm connecting to the trakt.tv api, I want to create a little app for myself that displays movies posters with ratings etc. 我正在连接到trakt.tv api,我想为自己创建一个小应用程序,显示评级等电影海报。

This is what I'm currently using to retrieve their .json file containing all the info I need. 这就是我目前用来检索包含我需要的所有信息的.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'];
}

Because the .json file is huge it is loading pretty slow. 因为.json文件很大,所以加载速度很慢。 I only need a couple of attributes from the file, like title,rating and the poster link. 我只需要文件中的几个属性,如标题,评级和海报链接。 Besides that I only need the first 20 or so. 除此之外,我只需要前20个左右。 How can I make sure to load only a part of the .json file to load it faster? 我怎样才能确保只加载.json文件的一部分来加载它?

Besides that I'm not experienced with php in combination with .json so if my code is garbage and you have suggestions I would love to hear them. 除此之外,我没有经验与php结合.json,所以如果我的代码是垃圾,你有建议,我很乐意听到他们。

Unless the API provides a limit parameter or similar, I don't think you can limit the query at your side. 除非API提供limit参数或类似参数,否则我认为您不能限制查询。 On a quick look it doesn't seem to provide this. 快速查看它似乎没有提供这个。 It also doesn't look like it really returns that much data (under 100KB), so I guess it is just slow. 它也看起来不像真的返回那么多数据(100KB以下),所以我猜它只是很慢。

Given the slow API I'd cache the data you receive and only update it once per hour or so. 鉴于API速度慢,我会缓存您收到的数据,并且每小时左右只更新一次。 You could save it to a file on your server using file_put_contents and record the time it was saved too. 您可以使用file_put_contents将其保存到服务器上的文件中,并记录它的保存时间。 When you need to use the data, if the saved data is over an hour old, refresh it. 当您需要使用数据时,如果保存的数据超过一个小时,请刷新它。

This quick sketch of an idea works: 这个想法的快速草图有效:

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