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

发布于 2024-10-07 13:40:29 字数 1073 浏览 0 评论 0原文

我正在尝试解析某个位置(本例中为亚特兰大)的最新 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>

所需的结果将是

  • Whatever The Trend Is
  • < /code>

    它大约 30% 的时间有效 - 但其他 70% 我收到此错误:

    Fatal error: Cannot use object of type stdClass as array in...

    经过一番谷歌搜索后,似乎 obj 必须是数组...我找到的唯一答案是将 $obj 行更改为 true ,如下所示:

    $obj = json_decode($result, true);
    

    但是,这只会给我这个错误:

    警告:为 foreach() 提供的参数无效...

    有谁知道如何将我的代码更改为“数组”,以便它能够 100% 地工作?

    I'm trying to parse the latest Twitter trend from a location (Atlanta in this case)

    Here's my code:

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

    The desired result would be <li class="atlanta">Whatever The Trend Is</li>

    It works about 30% of the time - but the other 70% I get this error:

    Fatal error: Cannot use object of type stdClass as array in...

    After some googling it seems the obj must be array... The only answer I've found is to change the $obj line to a true like this:

    $obj = json_decode($result, true);
    

    However, that simply gives me this error:

    Warning: Invalid argument supplied for foreach() in...

    Does anyone know how to change my code into an 'array' so that it will work 100% of the time?

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(1

    夏了南城 2024-10-14 13:40:29

    @肯:试试

    $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
    }
    

    @Ken: Try

    $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
    }
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文