Twitter API本地趋势分析 - stdClass错误

时间:2010-12-13 20:13:22

标签: php arrays parsing twitter stdclass

我正在尝试从一个位置解析最新的Twitter趋势(在这种情况下是亚特兰大)

这是我的代码:

<html>
  <head></head>
  <body>
    <?php
     $init = 'http://api.twitter.com/1/trends/2357024.json?count=1&callback=?&exclude=hashtags';
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL,$init);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
     $result = curl_exec($ch);
     curl_close($ch);
     $obj = json_decode($result);
     foreach ($obj[0]->trends as $trend) {
     echo "<li class=\"atlanta\">".$trend->name."</li>";
}?>
  </body>
</html>

期望的结果是<li class="atlanta">Whatever The Trend Is</li>

大约30%的时间可以正常工作 - 但是另外70%我得到了这个错误:

致命错误:不能将stdClass类型的对象用作...中的数组

经过一些谷歌搜索似乎obj必须是数组...我发现的唯一答案是将$ obj行更改为如下所示:

$obj = json_decode($result, true);

然而,这只是给了我这个错误:

  

警告:在......

中为foreach()提供的参数无效

有谁知道如何将我的代码更改为'数组',以便它可以100%的时间工作?

1 个答案:

答案 0 :(得分:0)

@Ken:试试

$obj = json_decode($result, true);
if (is_array($obj)) { 
    foreach ($obj[0]->trends as $trend) {
        echo "<li class=\"atlanta\">" . $trend->name . "</li>";
    }
} else {
   // failure case here
}