Isrg KB
The Best Way to Gain Knowledge

Twitter PHP API to get Trending Hashtags from a specific city

Recently, we developed a bot to tweet the articles published on Isrg Knowledge base to Twitter automatically after a specific and defined period of time. The bot has ability not only to post the tweets on the Twitter after fetching the entries from the database, but also to convert the tags of the post into hashtag. It was doing pretty well, but I was not satisfied as I wanted to include the trending hashtags from the Twitter into my Tweets, but there are hardly any documentations or tutorial to get the trending hashtags from Twitter so, I’d decided to write my own code which I’ve shared in this blog post to help you out in getting the trending hashtags from the Twitter using PHP API.


  • Basic Knowledge of PHP
  • Knowledge of JSON and Arrays
  • Twitter Consumer Key and Consumer Secret
  • Twitteroauth PHP library

Getting started

  1. Download the twitteroauth PHP library from the GitHub
  2. Extract the downloaded zip file of twitteroauth PHP library and rename the folder to twitteroauth
  3. Create a PHP file with the name of your choice (Example: hashtag.php) and paste the below code in your PHP file

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:

  1. Go to
  2. Choose the application which you would like to use (If there are new to the Twitter developer portal and there are no applications in your account, you can apply for a Twitter developer account in order to create an app on the Twitter)
  3. Click on the “keys and access tokens” tab on your applications page
  4. Note down the Consumer Key and Consumer Secret (You can generate the Consumer Key/Secret if you’ve not generated it).
  5. Open your PHP file in which you’ve pasted the above PHP code and replace the following contents:

  1. Save the file and run it

Customizing 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 numbers.

2. Changing the Geographical locations

You can change the geographical location by changing the value of $GeoLocleID to the desired location, city or country.

3. Changing the format of the hashtag

You can change the format 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