简体   繁体   中英

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.

This is what I'm currently using to retrieve their .json file containing all the info I need.

$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. 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. How can I make sure to load only a part of the .json file to load it faster?

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.

Unless the API provides a limit parameter or similar, I don't think you can limit the query at your side. 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.

Given the slow API I'd cache the data you receive and only update it once per hour or so. You could save it to a file on your server using file_put_contents and record the time it was saved too. 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM