Friday 16 May 2014

Zend Framework - Free Google Analytics API

Zend Framework - Free Google Analytics API

After making a successful website, we add an  google analytics code to track the activities on our website. It gives all tracking information from all geo regions on all the pages.
It help us to know daily, monthly, yearly visiter in different countries and list of pages which searched most.

But creating a report on the behalf of analytics data, is difficult stuff because it take a lot of lot of time.

Following are simplest way to get the google analytics data.
        $email = 'ADSENSE_GMAIL_USERNAME';
        $password = 'ADSENSE_GMAIL_PASSWORD';
        /** Get Connection with Analytics Account * */
        $client = Zend_Gdata_ClientLogin::getHttpClient($email, $password, Zend_Gdata_Analytics::AUTH_SERVICE_NAME);
        $service = new Zend_Gdata_Analytics($client);
        /** Get Connection with Analytics Account * */
        /** Get Analytics Account Information * */        
        $profileResults = $service->getDataFeed($service->newAccountQuery()->profiles())->current()->getExtensionElements();
        foreach($profileResults as $profileResult){
            $attributes = $profileResult->getExtensionAttributes();
            $name = $attributes['name']['value'];
            $value = $attributes['value']['value'];
                $profileId = $value;
            echo "$name : $value\n";
        /** Get Analytics Account Information * */
        /** Get Analytics Data */         
        $dimensions = array(

        $query = $service->newDataQuery()->setProfileId($profileId)
                ->addSort(Zend_Gdata_Analytics_DataQuery::METRIC_VISITS, true)
                ->addSort(Zend_Gdata_Analytics_DataQuery::METRIC_BOUNCES, false)
        echo "\nVisits : Bounce \n\n";
        foreach ($dimensions as $dim) {
                   $result = $service->getDataFeed($query); 
        }catch(Exception $e){
            echo $e->getMessage();die;

        foreach ($result as $row) {
            echo $row->getMetric('ga:visits') . "\t";
            echo $row->getValue('ga:bounces') . "\n";
        /** Get Analytics Data */

As an above example, you can extract all information from the Google Analytics API and stored in array or Object then can download into csv OR Excel format.