Search code examples
phpapiimdb

IMDB Api, retrieve title and plot only.


I found this site, that provides IMDB API: http://www.omdbapi.com

and for getting for example the hobbit's it's easy enough as this: http://www.omdbapi.com/?i=tt0903624

Then I get all this information:

{"Title":"The Hobbit: An Unexpected Journey","Year":"2012","Rated":"11","Released":"14 Dec 2012","Runtime":"2 h 46 min","Genre":"Adventure, Fantasy","Director":"Peter Jackson","Writer":"Fran Walsh, Philippa Boyens","Actors":"Martin Freeman, Ian McKellen, Richard Armitage, Andy Serkis","Plot":"A curious Hobbit, Bilbo Baggins, journeys to the Lonely Mountain with a vigorous group of Dwarves to reclaim a treasure stolen from them by the dragon Smaug.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTkzMTUwMDAyMl5BMl5BanBnXkFtZTcwMDIwMTQ1OA@@._V1_SX300.jpg","imdbRating":"9.2","imdbVotes":"5,666","imdbID":"tt0903624","Response":"True"}

The thing is that I only want for exmaple the title, the year and the plot information, and I wonder how I can only retrieve this.

I want to use PHP.


Solution

  • Here you go... simply decode the json, and pull out the data you need. If need be, you can re-encode it as json afterwards.

    $data = file_get_contents('http://www.omdbapi.com/?i=tt0903624');
    $data = json_decode($data, true);
    $data = array('Title' => $data['Title'], 'Plot' => $data['Plot']);
    $data = json_encode($data);
    print($data);
    

    Another way to do this (slightly more efficiently) is to unset unneeded keys, e.g.:

    $data = file_get_contents('http://www.omdbapi.com/?i=tt0903624');
    $data = json_decode($data, true);
    $keys = array_keys($data);
    foreach ($keys as $key) {
        if ($key != 'Title' && $key != 'Plot) {
            unset($data[$key]);
        }
    }
    $data = json_encode($data);
    print($data);