PHP JSON Twitter趋势

时间:2011-01-22 13:29:44

标签: php json twitter

任何人都可以通过这个PHP发现问题,屏幕上没有任何内容:

<?php
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

$url='http://search.twitter.com/trends.json';
$obj = json_decode(get_data($url));
foreach ($obj as $item) {
$trend = $item->name;
$link = $item->url;
echo "<a href='.$link.'>".$trend."</a>";
}
?>

1 个答案:

答案 0 :(得分:2)

你没有正确地循环收集。使用:

foreach ($obj->trends as $item) {

您的$obj是一个对象(只是stdClass),其trends属性是一组具有nameurl属性的对象。这反映了JSON的结构,如下所示:

{
    "trends": [
        {
            "name": "#yepthatsme",
            "url": "http://search.twitter.com/search?q=%23yepthatsme"
        },
        {
            "name": "Miley Citrus",
            "url": "http://search.twitter.com/search?q=Miley+Citrus"
        },
        /* lots more */
        {
            "name": "Keith Olbermann",
            "url": "http://search.twitter.com/search?q=Keith+Olbermann"
        }
    ],
    "as_of": "Sat, 22 Jan 2011 13:37:25 +0000"
}