Google Trends is an amazing tool which allows you to understand search interest in a specific topic over time. The ability to monitor these topics in specific regions is really useful for international content campaigns. It ultimately allows you to create engaging content by staying ahead of the curve and understand new trends as soon as they emerge.
Sadly, there is no official Google Trends API, we look at getting the trend data from an alternative tool. From there, we can discuss some of the options available and some of the transformations we ourselves can make to the raw data we have collected and use it in a web application or research project.
Briefly, it is useful to give a quick tech overview for the task at hand. The tool we will use to scrape the data utilises PHP and we also need NPM and we will use Packagist to install any packages we need. As we are using a server-side language, a virtual server would be required such as WAMP or MAMP. In terms of optional apps, it may be useful to have a database tool to store the raw data that is collected.
Introduction to a Google Trends Alternative
As mentioned earlier, Google Trends does not currently have an official API. So if you want to make a web application with its data, an unofficial tool will be required. For this task, we will use G-Trends by X-Fran, a great free tool that provides us with more than enough to get the data we need.
We will look at some of the features offered by G-Trends that mirror the functions of the official Google Trends application. For example, G-Trends provides options to receive data for Related Queries and Suggestions Autocomplete – both of which are great for keyword inspiration in your relevant industry or topic.
We will be making use of the Interest Over Time feature of Google Trends because we will be looking retrospectively at the trend data for a specific keyword, in a specific country, over the course of six years. With the historical data, we can make a few assessments and spot seasonality and other trends, which give us an insight into future opportunities.
Making the Interest Over Time G-Trends Request
Create a new project in the development environment of your choice and open the command line. Enter the following command to install the packages used by G-Trends:
Note – There can sometimes be SSL issues with local virtual servers. Please refer to the WAMP or MAMP guides on creating locally issues SSL certificates for your computer. Additionally, there may be interference with anti-virus apps blocking the download. To get round this, please refer to guides on your specific anti-virus software and how to allow WAMP / MAMP to be exempt from the security checks.
Running the command above with create the files for all the packages required as well as some composer configuration files. Inside this folder, we can make a subfolder and it can be called as appropriate – I will call it “example”. It is best to keep your working files separate from the folder with PHP packages for organisation and security reasons. Inside this folder, make an index.php file and add the line to include vendor’s autoload file. Then we include the GTrends class from the namespace to include GTrends in our project.
Once installed, the GitHub repository gives a nice example of setting up your options and deciding what data you want to collect. The example covers several of the controls seen on Google Trends, such as language, country, timeframe and time zone, as shown below.
Now, we will look at some of the specific options selected and a brief reason why they were chosen.
- Country Code (Geo) – The first option to set is the country code. This is available in Google’s documentation or you can use Google Trends and grab the codes from the URL. For example, the United Kingdom would be selected with GB.
- Language (HL) – Next is to select the language within the country. The language code is available in Google’s documentation. For example, British English would be selected as en-GB.
- Timeframe (Time) – Next, is to set the date range to a suitable period of time. Currently, it needs to be at least 6 years long in order to get the data split by each month. The range can be set by adding two dates in YYYY-MM-DD format e.g. 2019-05-01 2025-05-31.
- Search Topic (Category) – I keep the category set to 0 so any trends data collected is as broad as possible.
- Time Zone (TZ) – I also keep the time zone to 0 so it can default to the suitable time zone of the selected country. Also, because the timeline is over several years, the time zone does not come into play.
Once the options are set up, we create a new G-Trends request by creating a variable and passing the options as a parameter to the G-Trends function. Looking at the documentation, the G-Trends function we are using is getInterestOverTime. We pass the keyword as a parameter to tie the keyword to a country at a specific date range.
Processing the Raw Trends Data
Initial Review and Language Considerations
Now we have made the request, we want to do some basic formatting so we can review the data. First, we can use HTML <pre> tags to ensure the text output maintains the same indents, line breaks and spaces so we can read it more easily. We can use the json_encode() function to convert the PHP array into JSON format. Finally, JSON_PRETTY_PRINT adds the line breaks and indentation that the <pre> tags are preserving.
It is at this point, you could store the JSON data and then switch to using a language of your choice, if PHP is not your first pick. The new format is universally compatible with other languages, including front-end languages such as JavaScript. The way the data is processed depends on which development library is being used. The data can be processed using standard PHP or a PHP library such as CodeIgnitor. The data could be processed stored in a database using a package such as Medoo. For our example, we will use standard PHP for the sake of clarity.
Process the Raw Data With PHP
Using PHP, the data coming back from GTrends is already a PHP array so we can start working with it right away. An array is a common method of processing API requests and carrying out some manipulations later on. Next is to set a variable for the months data by looking inside the array we just created and reference the array keys of TIMESERIES, then data and finally timelineData. This way, we can focus out attention specifically on the part of the array which has the month scores we need.
To finish off the preparation, we can create an empty Trend Scores variable to store the score values in an array. Using the echo feature of PHP, we can create a heading for the section we will create on the page featuring the list of months and trend scores. Now the data has been reviewed, we can also comment out the <pre> tags we made earlier, as they are no longer required.
Now we use the variable storing the trend array data and cycle through each individual month using a foreach loop. Inside the loop, the date of the month can be accessed by using “time” array key. To process the raw data for your application, it would be a good idea to turn the date into a suitable format by using the date function. In this case, “Y-m-d” provides the date in a YYYY-MM-DD format.
Similarly, the trend score for the month is accessible with the “value” array key. Adding both the month name and the suitable score to a pair of variables enables us to use the values again later in the application. For instance, we can use echo to display the values on the screen. Appending a line break after each value will make the content more manageable. Also, putting a <hr> before the end of the loop will add a horizontal row under each month and score combination.
Now the data is displayed on the page, the text can be copied into a spreadsheet for further analysis or stored in a database. If different combinations are required, then the options at the top of the script can be amended such as keyword, country, language etc. If you wanted to make a scalable, automated solution, the list of combinations could be stored in a database and the script could be amended to dynamically retrieve data depending on what combination was required.
Now the data is displayed on the page, the text can be copied into a spreadsheet for further analysis or stored in a database. If different combinations are required, then the options at the top of the script can be amended such as keyword, country, language etc. If you wanted to make a scalable, automated solution, the list of combinations could be stored in a database and the script could be amended to dynamically retrieve data depending on what combination was required.
Do Not Burn API Credits, If You Do Not Have To
Our example has been using the data directly from the GTrends API and this works when retrieving fresh data for your chosen set of options. However, if you are working with the one set of sample data and editing a script to perform tests, it is not necessary to retrieve data from the API directly each time. You can create a variable with the sample raw data provided by GTrends and perform tests on this data instead of making calls to the API each time. This way, we can cut down on the number of API credits being used. Being efficient with credits means you are less likely to be blocked by the application or can reduce costs if an API is not free.
To amend our script to be more efficient, we want to create a DEBUG_MODE constant below the “use XFran” line. If the debug is true, we are testing with the sample GTrends data and not using any credits. If debug is false, testing is finished and we are getting data straight from the API. From there we can amend the script depending on whether debug is on or off. When debug mode is off, we can place the GTrends and getInterestOverTime functions inside a check that will only run when debug mode is off, as we only make API request if we are not testing. For when debug mode is on, we can copy the output of the array and set this to the gTrendsResponse variable. We can then set a second line where we convert the gTrendsResponse data to a PHP array using json_decode with the second parameter of true.
Now, we can switch debug mode on or off depending on whether live data is needed or not and API credits can be saved when doing some testing. The updated full script can be seen below with the additional debug checks added:
Sample Data Transformations
Now you have collected and processed the raw data, it is ready to be transformed and analysed as you see fit. There are a huge amount of transformations that could be done, here are a few potential ideas to get you started.
Six-Year Average (Median)
First, we can look at the average in terms of the median value out of our monthly trend scores. This cuts out any short term noise and gives a stronger understanding of the overall data set for the entire duration.
The first step is to use the sort() function to put the score values in ascending order. Next we need to get the index (rank in the list of scores) of the middle score. To do this, you wrap the trend scores in a count() function to get the number of months we are counting. Next we wrap that value in brackets and deduct 1 because PHP is zero-based so counts the index 0, 1, 2 and so on. Finally, we divide the value by two to get the middle value and we wrap this in a floor() function to round the number down and get a whole number instead of a decimal.
Six-Year Average (Mean)
Second, you could get the average mean over the six year period by dividing the total of the scores by the number of months in question. This is similar but distinct from the average median because the mean takes into consideration any abnormal spikes or drops in popularity.
To do this, you would array_sum the scores variable to get the total of all the scores combined. You would also want to wrap it in number_format so you can work with the values later on. Use the count function to get the total number of months and then divide the sum of the scores by the number of months to get the average.
Highest, Lowest and Range Scores
Another way of digesting the data is to get the lowest score, highest score and range in between. This method could allow you to see the range of trend scores and give a clearer understanding of the peaks and troughs of the data set.
To get the lowest value, use the min() function and wrap it around the $trendScores variable and this will return the smallest score in the list. Conversely, the max() function can be used to select largest value. Finally, to get the range between the two values, we create a variable for $scoreRange and then assign the highest score minus the lowest score.
Top 5 Months
An alternative action that could be taken is to get the top 5 scores and the suitable name of the month. The array would need to be amended so it has the month and the score e.g. “January 2026” → 88 and so on. This method enables seasonal trends to be spotted.
Call the scores array and wrap it in an arsort() function to place the scores in descending order and preserve the array keys. Second, create a variable for the top five scores and assign it to an array_slice() function. The first parameter is the trend scores and the second and third is 0 and 5 to select the first five on the list. Finally, set the last value to true as we want the key (month) to be retained.
Months Above a Specific Score
Following on from the average example, we can use this figure to collect the months that are above the average. Alternatively, the threshold could be manually set to a higher score if you wanted to measure the best performing months. This provides an opportunity to collect months performing at a higher level and insights can be gleamed based on the patterns of the months collected.
First, assign the average score variable to an array_filter() function. Inside, set the first parameter to the array of trend scores and set the second value to an anonymous function using $score as a parameter. This method allows each trend score to be looped through. Then, return the score if it is greater than or equal to the average – in this case, I used 50 as an example average.
Conclusion
Whilst we do not have an official Google Trends API, G-Trends by X-Fran is a great tool that gives us more than enough trend data for your web application or research document.
The beauty of the tool is being able to turn the data into JSON format. From there, you can use the development language of your choice. For easier analysis, I would recommend storing the data in a database or spreadsheet. From there you can connect it to a visualisation tool such as Google Data Studio and start enhancing your trend data.
If you are running an ongoing commercial operation, it may be a plan to get the data from a commercial partner. G-Trends is great for a one-off data collection or for establishing a conceptual MVP. However, the creator acknowledges it is an unofficial tool and it can be smart to get a reliable data partner such as Data For SEO or SERP API, so you can access reliable data on a longer timescale.
Ultimately, the ability to conduct ongoing monitoring of various trends lets you stay ahead of the curve and make smart, informed business decisions. Enjoy your croissants! 🥐