Search code examples
phpjsoncurlitunes

Search iTunes Music Library for a search term via API


All, I'm trying to allow a user to search for a song. Say the user is searching for Jack Johnson and I want to display all of the songs on iTunes by Jack Johnson. I know I need to construct a URL like the following:

http://itunes.apple.com/search?term=jack+johnson&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song

From a programming persepective, how would I send this to Apple? If I copy that URL into my browser I get some results. Based on those results, how could I parse those results so that I can display them back to the user? Would I want to use JSON, cURL, a combination of the two? What would be the most efficient way to do this?

Any help here would be greatly appreciated!


Solution

  • If I understand correctly what you want, maybe something like this:

    <?php
    if(isset($_POST['term']))
    {
        $term = urlencode($_POST['term']); // user input 'term' in a form
        $json =  file_get_contents('http://itunes.apple.com/search?term='.$term.'&limit=25&media=music&entity=musicArtist,musicTrack,album,mix,song');    
        $array = json_decode($json, true);
    
        foreach($array['results'] as $value)
        {
            echo '<p>';
            echo $value['artistName'].'<br />';
            echo $value['artistLinkUrl'].'<br />';
            echo $value['primaryGenreName'];
            echo '</p>';
        }
    }
    ?> 
    
    <form method="post">
        <input type="text" name="term" /><input type="submit" value="Go" />
    </form>
    

    For more $array value, try print_r($array);