PHP: iTunes API example.

This is a basic tutorial on how to search the iTunes API web service with PHP. This is particularly handy if you are looking for album artwork, artist singles or DVD covers.

Here is a simple example:


 * Search iTunes with PHP.
 * @param string $searchTerm
 * @return array|boolean Associative array. Or FALSE on failure.
function search($searchTerm){
    //Construct our API / web services lookup URL.
    $url = '' . urlencode($searchTerm);
    //Use file_get_contents to get the contents of the URL.
    $result = file_get_contents($url);
    //If results are returned.
    if($result !== false){
        //Decode the JSON result into an associative array and return.
        return json_decode($result, true);
    //If we reach here, something went wrong.
    return false;

//Use our custom function to search for 2Pac-related stuff.
$searchResults = search('2Pac');

//Loop through the results.
foreach($searchResults['results'] as $result){
    //Print out the album artwork / single cover.
        echo '<img src="' . $result['artworkUrl100'] . '">';

//var_dump the result for illustrative purposes.

As you can see, we created a custom function called “search”, which constructs an API call to the iTunes web service (we encode our search term by using the function url_encode). We then decode the result from the API into an associative array using the json_decode function.

Later on, we loop through the search results before printing out the album artwork (if it exists – in some┬ácases, it won’t).

All in all, it’s actually pretty simple!