Google Analytics PHP API (GAPI): obteniendo el número de visitas a las páginas
-
28-10-2019 - |
Pregunta
He estado trabajando en esto durante dos días y parece estar llegando a ninguna parte.
Estoy usando la clase GAPI Google Analytics PHP. Este es el código actual que tengo ahora:
$ga->requestReportData("[UID]",array('day'),array('visits'), array("day"));
Lo que quiero hacer es obtener el número de "PageViews" de los "últimos 7 días". Entonces la salida sería algo como:
<?php foreach($ga->getResults() as $result) { ?>
Date: <?php echo $result; ?>
Page Views: <?php echo $result->getPageviews(); ?>
<?php } ?>
Soy nuevo en la API de Google Analytics, así que no estoy seguro de por dónde empezar. ¡Gracias por cualquier ayuda!
Solución
Esto debería ayudarte
<?php
require 'gapi.class.php';
$gaEmail = 'youremail@email.com';
$gaPassword = 'your password';
$profileId = 'your profile id';
$dimensions = array('pagePath','country', 'region', 'city');
$metrics = array('visits');
$sortMetric=null;
$filter=null;
$startDate='2011-02-01';
$endDate='2011-02-28';
$startIndex=1;
$maxResults=10000;
$ga = new gapi($gaEmail, $gaPassword);
$ga->requestReportData($profileId, $dimensions, $metrics, $sortMetric, $filter, $startDate, $endDate, $startIndex, $maxResults);
$totalPageviews = $ga->getPageviews();
foreach ($ga->getResults() as $result) {
$visits = $result->getVists();
print $visits;
}
?>
Tenga en cuenta que apagará su verificación de 2 pasos para la cuenta de Google. Si no lo hace, le enviará un error de solicitud incorrecto a pesar de la validez de la información de su cuenta.
Otros consejos
Le gustaría hacer una adición a @Ladiesman217, podemos crear contraseñas específicas de la aplicación si tenemos una verificación de 2 pasos.
En lo que respecta a Gapi, he creado una clase que dará mucha información pero utilizando un par de métodos. Puedes descargar la clase aquí http://www.thetutlage.com/post=tut217
<?php
error_reporting(0); // it is important as filtering tend to leave some unwanted errors
include_once( 'class.analytics.php' );
define('ga_email','your_analytics_email');
define('ga_password','your_analytics_password');
define('ga_profile_id','your_analytics_profile_id');
// Start date and end date is optional
// if not given it will get data for the current month
$start_date = '2012-05-28';
$end_date = '2012-06-27';
$init = new fetchAnalytics(ga_email,ga_password,ga_profile_id,$start_date,$end_date);
$trafficCount = $init->trafficCount();
$referralTraffic = $init->referralCount();
$trafficCountNum = $init->sourceCountNum();
$trafficCountPer = $init->sourceCountPer();
?>
Primer método cuenta de tráfico le dará (visitas a página, visitas, tarifa de rebote, tiempo de tiempo del sitio, nuevas visitas)
Segundo método referencia le dará (URL de referencia y número total de hits de esa URL)
Tercer método Sourcecountnum Le proporcionará una fuente de tráfico como (tráfico directo, orgánico, referencia, feed, correos electrónicos y otros)
Último método fraude Proporcionará la misma información que la tercera con una diferencia aquí, la información estará en porcentaje.
Espero que sea de ayuda y hágamelo saber en caso de errores.
<?php
define('ga_email','you email');
define('ga_password','passworkd');
define('ga_profile_id','profile ID or View ID');
require 'gapi.class.php';
// pars to pass on Google Server Analytic Api
$start_date='2013-12-01';
$end_date='2013-12-31';
$ga = new gapi(ga_email,ga_password);
try {
$ga->requestReportData(ga_profile_id,
array('browser','browserVersion'),
array('pageviews','visits','visitors','visitBounceRate'),
$sort_metric=null, $filter=null,
$start_date,$end_date,
$start_index=1, $max_results=30);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
<table width='60%'>
<tr style="background-color:#00ff00;">
<th>Browser & Browser Version</th>
<th>Page Views</th>
<th>Visits</th>
<th>Visitors</th>
<th>Visit Bounce Rate</th>
</tr>
<?php
$i = 0;
foreach($ga->getResults() as $result):
//$ga->printfs($result);
if($i%2 == 0) $color = "#d3d3d3";
else $color = "#FFFFF";
?>
<tr style="background-color:<?php echo $color ?>">
<td><?php echo $result ?></td>
<td><?php echo $result->getPageviews() ?></td>
<td><?php echo $result->getVisits() ?></td>
<td><?php echo $result->getVisitors() ?></td>
<td><?php echo $result->getVisitBounceRate() ?></td>
</tr>
<?php
$i++;
endforeach
?>
</table>
<table>
<tr>
<th>Total Results</th>
<td><?php echo $ga->getTotalResults() ?></td>
</tr>
<tr>
<th>Total Page views</th>
<td><?php echo $ga->getPageviews() ?>
</tr>
<tr>
<th>Total Visits</th>
<td><?php echo $ga->getVisits() ?></td>
</tr>
<tr>
<th>Total Visitors</th>
<td><?php echo $ga->getVisitors() ?></td>
</tr>
<tr>
<th>Visit Bounce Rate</th>
<td><?php echo $ga->getVisitBounceRate() ?></td>
</tr>
<tr>
<th>Results Updated</th>
<td><?php echo $ga->getUpdated() ?></td>
</tr>
</table>