【问题标题】:Twitter Trends PHP推特趋势 PHP
【发布时间】:2011-02-23 17:47:13
【问题描述】:

我正在尝试使用http://api.twitter.com/1/trends/current.json?exclude=hashtags,但是遇到了一些问题。

所以,我正在尝试使用:

  <?php
$init = 'http://api.twitter.com/1/trends/current.json?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, true);


foreach ($obj[0]['trends'] as $trend) {
    print $trend['query'];
    echo "<br>";
    print $trend['name'];
    echo "<hr>";
}

?>

我收到了这个错误:

注意:未定义的偏移量:第 11 行 \index.php 中的 0

警告:在第 11 行为 foreach() \index.php 提供的参数无效

【问题讨论】:

    标签: php json api twitter


    【解决方案1】:

    您读错了 JSON。您需要执行以下操作:

    foreach ($obj['trends']['2011-02-23 18:00:00'] as $trend) {
        print $trend['query'];
        echo "<br>";
        print $trend['name'];
        echo "<hr>";
    }
    

    【讨论】:

      【解决方案2】:

      如果我没记错的话

      $obj = json_decode($result, true);
      

      将产生一个数组而不是一个对象。其次使用twitter api很简单:

      <?php
      function get_trends($woeid){
          return json_decode(file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json?exclude=hashtags", true), false); 
      }
      $data = get_trends(23424848); //23424848 is woeid for India...
      $trends = $data[0]->trends;
      echo "<ul>";
      if(!empty($trends)){
          foreach($trends as $trend){
              echo '<li><a href="'.$trend->url.'" target="_blank">'.$trend->name.'</a></li>';
          }
      }
      echo "</ul>";
      ?>
      

      【讨论】:

        猜你喜欢
        • 2010-12-21
        • 2012-05-08
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-28
        • 2021-06-17
        • 2020-02-05
        相关资源
        最近更新 更多