2012-12-27 39 views
1

我發現這個網站,它提供IMDB API: http://www.omdbapi.comIMDB Api,只檢索標題和情節。

,併爲獲得例如霍比特人的這是很容易,因爲這: http://www.omdbapi.com/?i=tt0903624

然後我得到的所有信息:

{"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/[email protected]@._V1_SX300.jpg","imdbRating":"9.2","imdbVotes":"5,666","imdbID":"tt0903624","Response":"True"} 

事情是,我只想爲例如標題,年份和情節信息,我想知道我只能檢索這個。

我想使用PHP。

回答

5

這裏你去...簡單地解碼json,並提取你需要的數據。如果需要,您可以將其重新編碼爲json。

$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); 

另一種方式來做到這一點(稍微有效)是來取消不必要的按鍵,例如:

$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); 
+0

當我嘗試頂級解決方案時得到了這個:「致命錯誤:不能使用類型爲stdClass的對象作爲數組在」 – user1133188

+0

這是因爲json_decode的默認值是作爲一個對象。我已經添加了一個編輯(只要它得到審查),通過將第二個參數設置爲數組進行解碼來修復該編輯。作爲替代方案,您可以使用第一個示例中的對象表示法訪問默認的json_decode數據,如下所示:''Title'=> $ data-> Title,'Plot'=> $ data-> Plot' – taswyn

0

OMDBAPI.com不再免費使用。正如你可以在他們的網站上閱讀:

05/08/17 - Going Private! Please go read the post on the Patreon page about this major change. 

這意味着你必須成爲捐助者才能訪問API。我使用了他們的API一年多了,現在停止了。如果您需要執行大量查詢,那麼我認爲成爲OMDBAPI的贊助商是個不錯的主意。不過,我在他的私人小項目中使用了他們的API。谷歌搜索了一下後,我發現了另一個API。以下是您可以使用的代碼:

<?php 
$imdbID = 'tt2866360'; 
$data = json_decode(file_get_contents('http://api.rest7.com/v1/movie_info.php?imdb=' . $imdbID)); 

if (@$data->success !== 1) 
{ 
    die('Failed'); 
} 
echo '<pre>'; 
print_r($data->movies[0]); 

我不隸屬於本網站。但是我使用這個API,所以如果有人可以回答一兩個問題。