2017-10-20 126 views
0

我想在特定位置回复Twitter趋势。再说说WOEID = 1如何使用PHP获取Twitter趋势

这是我的代码:

// 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返回错误。

我该如何解决这个问题?

+0

的可能的复制[PHP的:“注意:未定义的变量”,“注意:未定义的索引”和“注意:未定义的偏移量”](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined- index-and-notice-undef) – GrumpyCrouton

+0

我仍然无法找到解决方案.. –

+0

您试图访问不存在的内容。做'回声'

".print_r($news_array,true)."
“' – GrumpyCrouton

回答

0

的问题是在这条线:

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

它应该是:

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

我这是来自Twitter的JSON文件的格式...