We can use Core Reporting API to fetch top (Popular) URLs from Google Analytics. Using Google API PHP Client let’s create a simple PHP page that pulls website’s top URLs from Google Analytics and updates MySql table. Once you are familiar, I am sure you can do lot more, I mean just checkout the information you can retrieve in this Reporting API.
Let’s start by creating MySql table called google_top_pages, table contains 4 columns (id, page_uri, page_title, total_views). You can run this query in your PhpMyAdmin to have this table created.
This is important part:
- Create Google OAuth API Keys and get Client ID and secret.
- Enter redirect url in Google Redirect URI, or you will get redirect mismatch error.
- Enable Analytics API in Google APIs Console->Services Page.
In Google Analytics Settings below, enter your site’s Analytics profile id like this : “ga:ProfileID”. Enter number of results you want to fetch, you can play around with dimensions and metrics later and don’t forget to enter MySql details.
Updating Top Pages
If everything is set correctly in configuration file, PHP page below should run without any trouble. We can run this page once or twice a month to fetch top pages from Google Analytics, and store them in MySql database for later retrieval.
We need to authenticate user first, and once we have the access token, we can proceed further with Analytics services. Please go though comment lines to understand the process.
Retrieving Top URLs from DB
When the top URLs are stored in database, here’s how we can retrieve the records from database. You can display it anywhere you like, such as on the sidebar or footer of your website etc.
If you haven’t noticed, there’s a Highlights widget on the right sidebar of this page, that’s exactly how this script pulls the popular links of your website.