解析iTunes json,然后将其显示在网页上,并用PHP缓存


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

我正在做一个项目,需要从iTunes获取信息,缓存信息,并用PHP在网页上显示。我更喜欢使用curl,因为它看起来更快,但我更熟悉get_file_contents。json url的一个例子是http://itunes.apple.com/lookup?id=284910350.我可以抓取并解码它,但我在那里遇到了麻烦。

这是我的开始:

<?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>"; 
    }

?>

我可以打印数组或var_dump,但似乎无法获取任何值。在那之后,我需要缓存整个东西。如果可能的话,我希望将其设置为在新内容到达时获取新内容,或者在不加重服务器负担的情况下频繁安排。

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

这应该是你的第一条线索(确保你把通知记录在工作时可以看到的地方)。当您看到这一点时,您就知道您引用的数组不正确。

你的下一步应该是

var_dump($arr);

看看你要找的钥匙到底在哪里。

然后你应该看到你实际上需要

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

您尝试过json_decode函数吗?您应该能够使用cURL下载该页面的内容,将其存储在一个变量中,然后使用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>