In: PHP
April 12th, 2011.Have you ever wondered if you could let user see his website visits on his own admin page without having to leave backend of his system? I have…
Actually – the CMS I made for my clients (written in Zend Framework) has this option for quite some time, and users love it.
So – in order to implement this function on your own website (written in Zend Framework) I have shared following code. First – copy model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | class Default_Model_Analytics { public function auth() { $email = "your_email@domain.com"; $passwd = "your_password"; try { $client = Zend_Gdata_ClientLogin::getHttpClient($email, $passwd, "analytics"); }catch (Zend_Gdata_App_CaptchaRequiredException $cre) { echo 'URL of CAPTCHA image: ' . $cre->getCaptchaUrl() . "\n"; echo 'Token ID: ' . $cre->getCaptchaToken() . "\n"; return null; } catch (Zend_Gdata_App_AuthException $ae) { echo 'Problem authenticating: ' . $ae->exception() . "\n"; return null; } return new Zend_Gdata($client); } public function fetch($gdClient, $startDate = '2010-07-01', $endDate = null, $dimensions = array("ga:region", "ga:city"), $metrics = array("ga:visits", "ga:pageviews")) { if(empty($gdClient)) return false; if(empty($endDate)) $endDate = date('Y-m-d'); try { $reportURL = "https://www.google.com/analytics/feeds/data?ids=ga:" . $yourAccountNumber . "&" . "dimensions=" . @implode(",", $dimensions) . "&" . "metrics=" . @implode(",", $metrics) . "&" . "start-date={$startDate}&" . "end-date={$endDate}&" . "sort=-ga:visits"; $results = $gdClient->getFeed($reportURL); $titleRow = 1; // To output a row of column labels echo '<table>'; foreach ($results as $rep) { if ($titleRow) { foreach ($rep->extensionElements as $elem) { $titles[] = $elem->extensionAttributes["name"]["value"]; } echo "<tr><td>" . implode("</td><td>", $titles) . "</td></tr>\n"; $titleRow = 0; } $row = array(); foreach ($rep->extensionElements as $elem) { $row[] = $elem->extensionAttributes["value"]["value"]; } echo "\t<tr>\n\t\t<td>" . implode("</td><td>", $row) . "</td>\n\t</tr>\n"; } echo '</table>'; } catch (Zend_Exception $e) { echo "Caught exception: " . get_class($e) . "\n"; echo "Message: " . $e->getMessage() . "\n"; } } } |
Then – run following code in your controller so user can see Analytics results:
1 2 3 4 5 6 7 8 | $analyticsModel = new Default_Model_Analytics(); //get: date start and date end of Analytics results $postParams = $this->getRequest()->getParams(); if($this->getRequest()->isPost()) { $gdata = $analyticsModel->auth(); $analyticsModel->fetch($gdata, $postParams['year1'] . '-' . $postParams['month1'] . '-01', $postParams['year2'] . '-' . $postParams['month2'] . '-31'); } |
Notice: This is not the proper way to write code in Zend Framework, but is used as an example.