Search code examples
phpjsonparsingitunes

Parsing iTunes json, then displaying it on webpage, and caching it with PHP


I'm working on a project where I need to get info from iTunes, cache it, and display it on a webpage with PHP. I prefer to use curl, since it seems faster, but I'm more familiar with get_file_contents. An example of the json url is http://itunes.apple.com/lookup?id=284910350. I'm able to grab and decode it, but I'm having trouble from there.

Here's my start:

<?php

    $cas = curl_init('http://itunes.apple.com/lookup?id=284910350');
    curl_setopt($cas, CURLOPT_RETURNTRANSFER, 1);
    $jsonitunes = curl_exec($cas);
    curl_close($cas);

    $arr = json_decode($jsonitunes,true);
    foreach($arr as $item) {
        echo "kind: ". $item['kind'] ."<br>"; 
    }


?>

I can print the array, or var_dump it, but can't seem to grab any values. After that, I need to cache the whole thing. If possible, I'd like to set it up to grab new content when it arrives, or on a frequent schedule without weighing down the server.


Solution

  • PHP Notice:  Undefined index:  kind in /var/www/html/frank/scratch.php on line 9
    

    That should be your first clue (make sure you're logging notices somewhere where you can see them as you work). When you see that, you know you're referencing the array incorrectly.

    Your next step should be

    var_dump($arr);
    

    to see where the key you're looking for actually is.

    Then you should see that you actually need

    foreach($arr['results'] as $item) {