Search code examples
jsonapiitunes

itunes search store api


I want to get data from the API iTunes Store to my PHP file. In the search form you can fill the artist and title of the song. I want to show only the data from the song. This is my code:

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

i get this error: Notice: Undefined property: stdClass::$artworkUrl60 in.... Whats wrong with my code?


Solution

  • Because your $data Object doesn't contain an attribute named $artworkUrl60. Your HTTP query doesn't not work correctly, you should use double quote instead of single quote.

    // 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