如何使用Movie DB API在PHP中显示数据

时间:2017-06-19 04:45:37

标签: php api

这就是我现在所理解的一切:

如果我打开此网址:

https://api.themoviedb.org/3/movie/tt0137523?api_key=522cec782xxxxxxxxxxxxxxxxxxxx

我将在屏幕上显示以下数据:

{"adult":false,"backdrop_path":"/87hTDiay2N2qWyX4Ds7ybXi9h8I.jpg","belongs_to_collection":null,"budget":63000000,"genres":[{"id":18,"name":"Drama"}],"homepage":"http://www.foxmovies.com/movies/fight-club","id":550,"imdb_id":"tt0137523","original_language":"en","original_title":"Fight Club","overview":"A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.","popularity":9.884594999999999,"poster_path":"/adw6Lq9FiC9zjYEpOqfq03ituwp.jpg","production_companies":[{"name":"Regency Enterprises","id":508},{"name":"Fox 2000 Pictures","id":711},{"name":"Taurus Film","id":20555},{"name":"Linson Films","id":54050},{"name":"Atman Entertainment","id":54051},{"name":"Knickerbocker Films","id":54052}],"production_countries":[{"iso_3166_1":"DE","name":"Germany"},{"iso_3166_1":"US","name":"United States of America"}],"release_date":"1999-10-15","revenue":100853753,"runtime":139,"spoken_languages":[{"iso_639_1":"en","name":"English"}],"status":"Released","tagline":"How much can you know about yourself if you've never been in a fight?","title":"Fight Club","video":false,"vote_average":8.199999999999999,"vote_count":8036}

它显示了战斗俱乐部数据,因为我在网址tt0137523上放置了fightclub IMDB ID

现在,如果我去这个网址:

https://image.tmdb.org/t/p/w500/adw6Lq9FiC9zjYEpOqfq03ituwp.jpg

我会得到Fightclub的海报,因为我在网址中插入了adw6Lq9FiC9zjYEpOqfq03ituwp这个密钥,我从数据中找到了这个密钥。

但是如何使用PHP代码?

给我看一个小型演示:

如何在此代码中显示图像?

<?php

$posterkey = somethinghere, which gets poster key 
echo "<img src='https://image.tmdb.org/t/p/w500/".$posterkey.".jpg
'></img";
?>
</body>

编辑:我也制作了这段代码,但不知道如何使用它

<?php
$requestsDone = 0;
$maxRequests = 2;

while ($requestsDone < $maxRequests) {
        $requestsDone++;

    echo "Request number: ".$requestsDone."<br>";

    $response = file_get_contents("https://api.themoviedb.org/3/movie/".mt_rand(500,996)."?api_key=522xxxxxxxxxxxxxxxxxxxxx");
    $response = json_decode($response);
    print_r ($response);
    echo "<br><br><br>";
}
?>

1 个答案:

答案 0 :(得分:1)

此代码有效。如果你还没有,试着弄清楚有什么不同。

$key = "<REDACTED>";

$json = file_get_contents("https://api.themoviedb.org/3/movie/tt0137523?api_key=$key");

$result = json_decode($json, true);

$poster_path = $result["poster_path"];

echo "<img src=\"https://image.tmdb.org/t/p/w500$poster_path\">";

// Output:
// <img src="https://image.tmdb.org/t/p/w500/adw6Lq9FiC9zjYEpOqfq03ituwp.jpg">

<强>更新

我认为问题是您在调用true时错过了第二个参数json_decode。传递它会得到一个关联数组而不是一个对象,所以你可以像我上面那样索引它。