Recently, we developed a bot to tweet the articles published on isrg KB to Twitter automatically after a specific and defined period. The bot has the ability not only to post the tweets on Twitter after fetching the entries from the database but also to convert the tags of the post into the hashtag. It was doing pretty well, but I was not satisfied as I wanted to include the trending hashtags from Twitter into my Tweets. Still, there are hardly any documentation or tutorial to get the trending hashtags from Twitter so, I’d decided to write my code which I’ve shared in this blog post to help you out in getting the trending hashtags from the Twitter using PHP API.
Twitter API to fetch hashtag from specific city or country using PHP:
Prerequisite:
Getting started
<?php $ConsumerKeyAPIKey="YOUR CONSUMER KEY WILL BE HERE"; $ConsumerSecretAPISecret="YOUR SECRET KEY WILL BE HERE"; $NumberOfTags=5; //keep as minimum as possible $GeoLocleID="20070458"; require "twitteroauth/autoload.php"; use Abraham\TwitterOAuth\TwitterOAuth; $connection = new TwitterOAuth($ConsumerKeyAPIKey, $ConsumerSecretAPISecret, $access_token, $access_token_secret); $statues = $connection->get("trends/place", ["id" => $GeoLocleID]); $stringgerr=""; $i=1; foreach($statues as $hash) { $inner=$hash->trends; foreach($inner as $in) { $value=$in->name; if (strpos($value, '#') !== false) { $value=$value; } else { $value="#".$value; } $stringgerr.=str_replace(" ","_",$value)." "; if($i==$NumberOfTags) break; $i++; } if($i==$NumberOfTags) break; } echo $stringgerr;
OUTPUT: #PhirSeModiSarkar #INvsAUS #Chhindwara #Amritsar #NirankariBhawan
Generating Twitter Consumer Key (API Key) and Consumer Secret
To Generating Twitter Consumer Key (API Key) and Consumer Secret:
<?php $ConsumerKeyAPIKey="Replace this with your consumer key"; $ConsumerSecretAPISecret="Replace this with your consumer secret";
Customising the hashtags
1. Increasing the numbers of tweets
You can increase or decrease the numbers of hashtags you want by changing the value of $NumberOfTags
To the desired quantities.
2. Changing the Geographical locations
You can change the geographical area by changing the value of $GeoLocleID
To the desired location, city or country.
3. Changing the format of the hashtag
You can change the composition of the hashtag by altering the value of $stringgerr
string the code.
That’s all folks. You can share your feedback and suggestions at @isrgrajan