Reputation: 37
I'm trying to make a movie list where is movie name and I'm trying to get imdb ratings, from url (database) and code works. But my problem is that if I have 50 movies in the list, this code makes 50 different omdb api calls and it slows down my site very well.
So how I can store/cache ratings? I'm not good for cache thins at all. Thanks :)
if (($row["imdb"] != "") AND (strpos($row["imdb"],'imdb')) AND
(strpos($row["imdb"],'title'))) {
$imdbID = ltrim(strrchr($row["imdb_url"],'tt'),'tt');
$imdbID = preg_replace("/[^A-Za-z0-9]/", "", $imdbID);
$omdbapi_key = 'API_KEY';
$url = file_get_contents("https://www.omdbapi.com/?i=tt" . $imdbID . "&apikey=" . $omdbapi_key);
$omdb = json_decode($url, true);
$imdb_rating = "<a target='_blank' href='https://www.imdb.com/title/tt" . $imdbID . "'>Rating: " . $omdb['imdbRating'] . " / 10</a>";
Now I can write cache file for just one movie. I don't know how I can add multiple movie api calls in one file. I have form where I add movie (Title, imdb url). I think I need rewrite whole file when I add new movie.
Update:
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);
if( file_exists($cacheFile))
{
$omdb = json_decode(file_get_contents($cacheFile), true);
}
else
{
$url = file_get_contents("https://www.omdbapi.com/?i=tt".$imdbID."&apikey=" . $omdbapi_key);
file_put_contents($cacheFile, $url);
$omdb = json_decode($url, true);
}
Upvotes: 0
Views: 193