pChart Revisited with Google Analytics

Back in December, SitePoint published an introductory article I wrote on pChart, a PHP library that creates eye-catching anti-aliased charts. A reader suggested that other articles might follow with further examples, and so I decided to write this one with a handy device for visually checking website statistics with the help of Google Analytics.

Google Analytics’ API

As most people know, Analytics is Google’s tracking tool that gathers such data like the number of visitors, unique visitor, pages per visit, and country of visitors for your website. Adding Analytics requires only the creation of an account, a profile for each website, and the addition of some JavaScript code in the page(s) you want to track. If you are new to all this then please visit Google Analytics’ Help Center to learn more about setting up your accounts and getting the tracking code. Once the tracking has been deployed for a short while, you can visit the Analytics website and view the current stats for your site(s).

Also, Google Analytics has an API which your script can invoke from a GET request and receive a JSON string as response. This string, once decoded, supplies data that can be manipulated by a server-side language like PHP. For example, if you want to check the traffic statistics often and regularly for several of your sites, you can build a personal dashboard in PHP that captures the required data through the Analytics API and display it.

--ADVERTISEMENT--

While the tracking code is quite straightforward to set up and use, the API is a bit more complex. Fortunately, Google and other developers provide a number of client libraries, like GAPI, the Google Analytics PHP5 Interface which is simple to use:

The first line above creates a gapi object and with it a connection to the API. The email and password required is the same you used to login and create your Analytics account. The second line invokes the method that grabs data proper. It has three mandatory arguments: the profile ID, the dimensions, and the metrics. The profile ID can be obtained from Analytics’ control panel, the same one you used to create the account. Click on the set-up icon at the right side of the menu bar, the choose the profile and click on “Profile Settings”. The profile ID is under the General Information header.

Dimensions specify the kind of report you want. For example, the dimension “date” will breakdown all of the results by date. Metrics is the information you’re after, in this case, “visitors” and “newvisits”, the latter being the percentage of first time visitors with respect to the total visitation. See the API documentation for a complete list of dimensions and metrics.

Graphing Visits

Let’s assume I want to track three websites: castleofargh.com, knightsofni.com and thecamelotfollies.com. Assuming tracking has been set up for each site, we begin to create the dashboard application by grabbing GAPI’s latest version from their download page and extracting the contents of the zipped file onto the server that will host the dashboard. Once this is done, I can write the script, which is made even simpler thanks to pChart.

Note that pChart must be included after the session has been opened and before anything is sent to the browser otherwise “headers already sent by…” errors will arise.

Afterward, we’ll need to set up some configuration data and initialize some useful arrays. I’ve started with an array which holds the names and profile IDs of the three websites we’ll be displaying information for, and then initialized arrays to store the names of the domains, the number of visits, and the number of new visitors.

The line above queries the API for all visits and new visitors figures for today. The two null parameters are for filtering and sorting formats and are required here only because they come before the date limits in the function’s definition statement.

reportRequestData() returns an object with one array for each day of the report. Since we’re interested only in a single date (the $startDate and $endDate values are the same), the inner loop will run only once.

At this point we have all three arrays filled with the relevant data. We’ll comes the fun part of using pChart to create a pie chart to show the percentage each of the three websites have in the day’s gross visitation.

The subsequent lines define the “points” of the graph – which for the pie chart are expressed as the angle of each sector of its circle – and the names of each website, that will be displayed as labels. Note that though the figures are presented as absolute values, pChart will later be instructed to display them as percentages.

The canvas has been specified as 700 pixels wide by 490 pixels high and will data from the dataset $myPieData will be plotted to it. The boundary is placed one pixel inside the canvas. The graph area proper was defined with a 50px margin with respect to the image object canvas.

Next, create a string to hold the picture’s title and generate the corresponding text:

The drawText() method places a rectangular box “pinned” to the canvas at x pixels from the left and y from the top side of the chart object area. The position on the box where it will be pinned is given by the align attribute. Above, the text area with the plot descriptor ($title) has the middle point of its top border placed at a point 350 px from the left and 3px from the top border of the canvas. I also added a grayish background rectangle with borders 50px away from the canvas’ limits.

Now let’s define a nice font and create the pie chart object. Later it will be rendered as a PNG image:

In addition to the pie chart, I want a stacked bar chart to visually show the number of new visitors with respect to the total of visits. The following lines should be easy to understand but please notice that now we have 2 data series, one for visits (as for the pie chart) and another for new visitors:

Summary

Demo code for this article is available on GitHub for you to play with and experiment. pChart can be used for creating application as simple as these but also a full-fledged dashboard for controlling any sort of process that can be measured and presented via an API. Use any sort of refresh mechanism (such as a JavaScript reload or a meta refresh) and the script you produce can continuously display updated statistics.

Armando Jeronymo has a B.Sc. in Electronics Engineering from Rio de
Janeiro's Ursuline University and a US Associate degree in Risk
Management. He started coding in a TI-59 calculator in the early 80's.
He then learned and forgot Sinclair Basic, Fortran, Algol and MS
Basic. For ten years he did not write code but worked with insurance
and reinsurance in his native Brazil and London. Then he went back to
programming to find out everything was different. He began by getting
to know HTML to create some material on aviation instruction. He then
learned Delphi's Pascal in order to create some financial
applications.
He began experimenting with server-side languages about the turn of
the Century, first with ASP but soon moving to PHP. He wrote his first
MySQL web application in about 2004. He switched to Linux in 2005
(Ubuntu 5.10 to be more exact) and has been developing LAMP systems
since then.
He is a Private Pilot and, whenever possible, a FlightGear flyer. He
loves classical music and jazz (including Bossa Nova) and old movies.
Besides computing he is professionally interested in business
management and a follower of Peter Drucker's teaching. Married and
father of a girl he is also an active member of his Rotary Club.