2017-10-20 179 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文件的格式...