Google Analytics API v3 how to extract values? - php

I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;

$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working

Related

Create a bidimensional array in php

I confess that I am a beginner. My goal is to be able to summarize in a two-dimensional table the amount per month (in column) for each class (in line). After doing a lot of research, I arrived at this stage in my project.
My problem is , I get the result with months repeating in columns like here.
Here is my code.
This is my sql code : "SELECT classe, mois, sum_ec FROM journal"
This is my php code :
<?php
$tableau = array();
$tblClasse = array();
$rt = mysqli_query($db, $req_sit);//execute la requete
while ($row = $rt->fetch_assoc()){ //forme le tableau
$tableau[$row['classe']][$row['mois']] = $row['sum_ec'];
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
}
echo '<table border="1">
<tr>
<th> </th>';
foreach ($tblClasse as $classe) {
echo '<th>' . htmlspecialchars($classe) . '</th>';
}
echo '</tr>';
foreach ($tableau as $mois=>$value) {
echo '<tr>';
$new_line = TRUE;
foreach ($tblClasse as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
$display = isset($value[$classe]) ? $value[$classe] : " ";
echo '<td>' . $display . '</td>';
}
echo '</tr>';
}
?>
Can someone tell me what mistake I made?
The problem is in this part of your code:
if (!in_array($row['classe'],$tblClasse)) {
$tblClasse[] = $row['mois'];
}
You are adding months (Fev, Mar) to the array and trying to check if it contains classes (PS, MS etc.) which is impossible, and this condition always returns true, so Feb is added to the $tblClasse array at each iteration. You must either check months or classes and add months or classes to the array respectively. And if you want the array to contain unique values (for example, months), use keys instead of values:
if (!array_key_exists ($row['mois'],$tblClasse)) {
$tblClasse[$row['mois']] = 1;
}
Where 1 can be replaced with any other value.
In the further part of your code use the keys, not values of $tblClasse array to form the table heading.
foreach (array_keys ($tblClasse) as $mois) {
echo '<th>' . htmlspecialchars($mois) . '</th>';
}
Eureka! It worked. I just had to change the line for the values ​​to "array_keys"
foreach (array_keys($tblClasse) as $classe) {
if ($new_line) {
echo '<td>' . $mois . '</td>';
$new_line = FALSE;
}
as well and boom! It's perfect. Thank you very much my dear. You have given me a lot of happiness.

How to format the php code to display this better

I have this code:
$sql = 'SELECT * from page';
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($result)) {
echo '<table><tr>';
foreach ($rows[0] as $columnName => $value) {
echo '<th>' . $columnName . '</th>';
}
echo '</tr>';
foreach ($rows as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
This code is working fine. But since my table is huge, it is appearing to be very very clumsy - almost unreadable. And I don't know how to make it appear better. I tried adding spaces and tabs but to no use. I can't understand how to do it. I got this code from my friend. Can anyone modify the code so as to add at least a tab space between every column. Help would be really appreciated.
You can for example do the following:
instead of
echo '<table><tr>';
use
echo '<table border="1"><tr>';
It will put border on your table and it will be easier to differentiate between cells

PHP converting JSON file into excel table is formatted incorrectly

I have made a PHP file that takes this JSON-based file: http://www.yellowpages.com.iq/ajax/get/register/Categories.php
and converts it into an excel-formatted-table with the formatting of (.cvs) using this code :
$contents = file_get_contents('http://www.yellowpages.com.iq/ajax/get/register/Categories.php');
$data = JSON_decode($contents);
$excel_file = fopen("file.csv", "a+");
$table = "<table border='1'>";
foreach($data as $elem) {
$table .= "<tr>";
foreach($elem as $key => $prop) {
$table .= "<th>$key</th>";
$table .= "<td>$prop</td>";
fwrite($excel_file, "$key,$prop\n");
}
$table .= "</tr>";
}
$table .= "</table>";
echo $table;
But the problem being, is it takes the data and displays it correctly, although it tends to format it like so: id 1
category Advertising
id 2
category Agriculture & FoodÂ
id 3
category Air condition
id 4
category Airlines
id 5
Aluminium & Glass
Instead of what I'm trying to make it look like which I made manually:
Any help would be appreciated!
You could change the code using fputcsv, which takes care of double quotes and escaping them.
For that you need to get the JSON as an associative array (provide the second argument true):
$data = JSON_decode($contents, true);
And then the loop you have would be replaced with this:
// "loop" for the header (only 1 iteration)
foreach($data as $elem) {
$table .= "<tr><th>" . implode("</th><th>", array_keys($elem)) . "</th></tr>";
fputcsv($excel_file, array_keys($elem));
break; // only need one row for header
}
// Restart loop for the data
foreach($data as $elem) {
$table .= "<tr><td>" . implode("</td><td>", $elem) . "</td></tr>";
fputcsv($excel_file, $elem);
}

PHP While Loop/Foreach Loops

I have a question on a different way to wright this code because its not doing what I want it to do..
I am creating a forum list that will display the section under that category. Well this is the issue as you can see that I have an If () {}Else {} statement that is being used to put the information in that list I want. The problem is that I need to add a special class to the last section under that category that will be called last-tr. Now my issue that I have is all the information is making it to the screen but the class is only applied to the last row and now the last row of all the category's which is what i'm looking for.
So something like this,
Welcome Center
Introduce Yourself
Say Hello To our Admins (last-tr)
Game
COD
BF4 (last-tr)
Code
PHP
Java
PDO (last-tr)
but what my code is giving me is
Welcome Center
Introduce Yourself
Say Hello To our Admins
Game
COD
BF4
Code
PHP
Java
PDO (last-tr) <- Just that one.
Here is the code
<?php
include '../../core/init.php';
include '../../includes/head.php';
//Getting Categories under Welcome
$db = DB::getInstance();
$user = New User();
$forum = New Forum();
$list = '';
$category = $db->query('SELECT * FROM forum_categories');
foreach ($category->results() as $category) {
$list .= '<thead>';
$list .= '<tr>';
$list .= '<th class="titles">' . $category->title . '</th>';
$list .= '<th>Last Post</th>';
$list .= '<th>Topics</th>';
$list .= '<th>Replies</th>';
$list .= '</tr>';
$list .= '</thead>';
$list .= '<tbody>';
$sections = $db->query("SELECT * FROM forum_section WHERE category_id = '$category->id'");
foreach ($sections->results() as $section) {
$x = 0;
if ($x < $sections->count()) {
$list .= '<tr>';
$list .= '<td>';
$list .= '<a href="/category.php?id='. $section->id .'">';
$list .= '<img scr="/images/icons/iconmonstr/intro.png">';
$list .= '</a>';
$list .= '' . $section->title . '';
$list .= '<span>' . $section->desc . '</span>';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
$x++;
}else {
$list .= '<tr class="last-tr">';
$list .= '<td>';
$list .= '' . $section->title . '';
$list .= '</td>';
$list .= '<td> Nasty </td>';
$list .= '<td> 0 </td>';
$list .= '<td> 0 </td>';
$list .= '</tr>';
}
}
$list .= '</tbody>';
}
?>
<link rel="stylesheet" href="/css/fourms.css">
<title>Forums</title>
</head>
<body>
<?php include '../../includes/header.php'; ?>
<section id="main_section">
<section id="main_content">
<div id="forum-section">
<table class="forumlist">
<?php echo $list; ?>
</table>
</div>
</section>
</section>
<?php include('../../includes/footer.php'); ?>
Your if-statement should be if ($x < $sections->count()-1) because the last index of an array is always count-1 due to starting at 0.
OR
You could also fix it here by starting $x at 1, since you are using a foreach with the counter on the side, so its not like you'll get an out of index error. In other words:
foreach ($sections->results() as $section) {
$x = 1;
if ($x < $sections->count()) {
...
$x++;
}else {
...
}
}
But going with the first option is probably more straight-forward.
You are testing against your overall class not the data within the class.
$sections->count() is counting all of the sections not the entries in teh one section you are dealing with.
You need to test the count of the singular section
So if you had
$sectionsAll = array(
sectionOne = array( 1, 2, 3),
sectionTwo = array( 1, 2, 3),
sectionThree = array( 1, 2, 3)
);
You are currently testing on $sectionsAll, you need to check against sectionOne, sectionTwo, sectionThree

Google Analytics Core Reporting API PHP Query

This is my first attempt to work with the Core Reporting API. I have successfully made it through the Hello Analytics tutorial and making API requests with no issue. My problem lies with querying the API for using Dimensions, Metrics, and Filters. Below is the code I am working with.. I am able to display how many visitors I have between the first of the month and the current day. Then it displays how many of these came from organic search. I am hoping someone can give me an example on querying the API with a more complex request.. perhaps including Dimensions, Metrics, Filters.. and then displaying then in rows. Any help is much appreciated. Below is my code so far...
//QUERY THE CORE REPORTING API
function getResults($analytics, $profileId, $first_day, $today) {
return $analytics->data_ga->get(
'ga:' . $profileId,
$first_day,
$today,
'ga:visits, ga:organicSearches');
}
//OUTPUT THE RESULTS
function printResults(&$results) {
if (count($results->getRows()) > 0) {
$profileName = $results->getProfileInfo()->getProfileName();
$rows = $results->getRows();
$visits = $rows[0][0];
$organic = $rows[0][1];
print "<h1>$profileName</h1>";
echo '<table border="1" cellpadding="5">';
echo '<tr>';
echo '<td>Visits</td>';
echo '<td>Organic</td>';
echo '</tr>';
echo '<tr>';
echo '<td>'. $visits . '</td>';
echo '<td>'. $organic . '</td>';
echo '</td>';
echo '</table>';
} else {
print '<p>No results found.</p>';
}
}
Here is the code:
$optParams = array(
'dimensions' => 'ga:date,ga:customVarValue1,ga:visitorType,ga:pagePath',
'sort' => '-ga:visits,ga:date',
'filters' => 'ga:visitorType==New',
'max-results' => '100');
$metrics = "ga:visits";
$results = $analytics->data_ga->get(
'ga:' . $profileId,
'2013-03-01',
'2013-03-10',
$metrics,
$optParams);
For displaying the result:
function getRows($results) {
$table = '<h3>Rows Of Data</h3>';
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No results found.</p>';
}
return $table;
}
You can have better understanding if you try to get this demo working.
Also refer to this code
This is the definition of data_ga->get function in the api source.
public function get($ids, $startDate, $endDate, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'start-date' => $startDate, 'end-date' => $endDate, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Analytics_GaData");
}
complete parameter list is here
all parameters except ids,startdate, enddate and metrics are optional and needs to be sent as associative array as 5th argumant of get function.

Categories