使用PHP将Google Analytics数据传输到MySQLi数据库的步骤如下:
require_once 'path/to/google-api-php-client/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('path/to/credentials.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setRedirectUri('http://localhost/oauth2callback.php');
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit;
$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($accessToken);
$analytics = new Google_Service_Analytics($client);
$response = $analytics->data_ga->get(
'ga:YOUR_VIEW_ID',
'2022-01-01',
'2022-01-31',
'ga:sessions'
);
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if ($mysqli->connect_errno) {
die('Failed to connect to MySQL: ' . $mysqli->connect_error);
}
$mysqli->query('CREATE TABLE IF NOT EXISTS analytics_data (
date DATE,
sessions INT,
PRIMARY KEY (date)
)');
foreach ($response->getRows() as $row) {
$date = $row[0];
$sessions = $row[1];
$mysqli->query("INSERT INTO analytics_data (date, sessions) VALUES ('$date', $sessions)");
}
$mysqli->close();
以上是使用PHP将Google Analytics数据传输到MySQLi数据库的基本步骤。你可以根据实际需求进行修改和扩展。在这个过程中,你可能需要使用其他PHP函数和技术来处理数据和错误处理。
领取专属 10元无门槛券
手把手带您无忧上云