douliang1891 2011-01-22 13:29
浏览 35
已采纳

PHP JSON Twitter趋势

Can anyone spot the problem with this PHP, nothing appears on the screen:

<?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条回答 默认 最新

  • doulai7239 2011-01-22 13:40
    关注

    You're not looping over the collection properly. Use:

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

    Your $obj is an object (just a stdClass) with a trends property which is an array of objects with name and url properties. This reflects the structure of the JSON which looks like:

    {
        "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"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度