如何使用PHP获取Twitter趋势

时间:2017-10-20 18:28:33

标签: php arrays json api twitter

我希望在特定位置回应推特趋势。假设woeid = 1

这是我的代码:

// Twitter App OAuth
    require_once('TwitterAPIExchange.php');
    $settings = array(
        'oauth_access_token' => "",
        'oauth_access_token_secret' => "",
        'consumer_key' => "",
        'consumer_secret' => ""
        );

// Get Trends
    $url = "https://api.twitter.com/1.1/trends/place.json";
    $requestMethod = "GET";
    $getfield = "?id=1";
    $twitter = new TwitterAPIExchange($settings);
    $myfile = fopen("hashtags.json", "w") or die("Unable to open file!");
    $txt = $twitter->setGetfield($getfield)
             ->buildOauth($url, $requestMethod)
                 ->performRequest();
    fwrite($myfile, $txt);

// echo Trends
    $x = 0;
    while($x <= 5) {
    $news_url = 'hashtags.json';
    $news = file_get_contents($news_url);
        $news_array = json_decode($news, true);

    $Hashtag = $news_array["trends"]["0"]["name"];

    echo $Hashtag;
    $x++;
    }

问题是:此行:$Hashtag = $news_array["trends"]["0"]["name"];,返回时出现Notice: Undefined index: trends in /home/user/public_html/Hashtag.php on line 30错误。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

问题在于这一行:

$Hashtag = $news_array["trends"]["$x"]["name"];

应该是:

$Hashtag = $news_array["0"]["trends"]["$x"]["name"];

我是来自twitter的JSON文件的格式......