开发者

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'开发者_JAVA百科);
    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.


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) {


Have you tried the json_decode function? You should be able to use cURL to download the contents of that page, store it in a variable, then use json_decode.


<pre>
<?php

    $ch = curl_init("http://itunes.apple.com/lookup?id=284910350");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($ch);
    curl_close($ch);

    $jsonDecoded = json_decode($content, true);
    echo $jsonDecoded['results'][0]['artistName'];

?>
</pre>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜