2017-02-12 97 views
0

我想從API iTunes Store獲取數據到我的PHP文件。在搜索表單中,您可以填寫歌曲的藝術家和標題。我只想顯示歌曲中的數據。這是我的代碼:iTunes搜索商店api

$title = $_POST["title"]; 
$artist = $_POST["artist"]; 
$query_string = urlencode($title); 
$query_string2 = urlencode($artist); 
$json = file_get_contents('https://itunes.apple.com/search?term=$query_string&term=$query_string2'); // this WILL do an http request for you 
$data = json_decode($json); 

echo "<div class='container' id='movies'>"; 
echo "<div class='col-md-4' id='movie'>"; 
echo "<img src='" .$data->artworkUrl60. "' width='200'>"; 
echo "<h4>" .$data->artistName. " - " .$data->trackName. "</h4>"; 

我得到這個錯誤:注意:未定義的屬性:stdClass的:: $ artworkUrl60中.... 請告訴我錯我的代碼?

回答

1

因爲您的$ data對象不包含名爲$ artworkUrl60的屬性。 您的HTTP查詢無法正常工作,您應該使用雙引號而不是單引號。

// For limit you can add 'limit' parameter 
$json = file_get_contents("https://itunes.apple.com/search?term=$query_string&term=$query_string2&limit=20"); 
// OR concatenation 
// $json = file_get_contents('https://itunes.apple.com/search?term='.$query_string.'&term='.$query_string2); 
$data = json_decode($json); 

if (0 == $data->resultCount) { 
    echo 'No result found ! '; 
} 
else { 
    foreach ($data->results as $row){ 
     echo "<div class='container' id='movies'>"; 
     echo "<div class='col-md-4' id='movie'>"; 
     echo "<img src='" .$row->artworkUrl60. "' width='200'>"; 
     echo "<h4>" .$row->artistName. " - " .$row->trackName. "</h4>"; 
    } 
} 

https://affiliate.itunes.apple.com/resources/documentation/itunes-store-web-service-search-api/#searchexamples

+0

後續代碼var_dump給所有的陣列。但是,當我這樣做:。$ data-> artistName。我得到相同的錯誤 –

+0

您應該添加一個foreach循環 –

+0

它的工作原理,謝謝! –