首先获取百度开发者账号并创建应用以获得client_id和client_secret,接着通过OAuth 2.0流程使用授权码获取access_token,然后利用该token调用百度统计RESTful API,发送POST请求至getData接口,传入site_id、日期范围及所需指标(如pv_count、visitor_count),最后解析返回的JSON数据并输出结果;需注意token有效期、API调用频率限制及错误处理。

要在PHP中调用百度统计API获取网站统计数据,需要理解其认证机制和接口调用方式。百度统计使用OAuth 2.0进行身份验证,并通过RESTful API提供数据查询功能。以下是实现步骤和代码示例。
要调用百度统计API,必须先完成以下准备工作:
使用client_id和client_secret请求access_token:
$clientId = 'your_client_id';
$clientSecret = 'your_client_secret';
$redirectUri = 'your_callback_url';
$code = 'authorization_code'; // 用户授权后返回的code
$tokenUrl = "https://openapi.baidu.com/oauth/2.0/token";
$params = [
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $clientId,
'client_secret' => $clientSecret,
'redirect_uri' => $redirectUri
];
$response = file_get_contents($tokenUrl . '?' . http_build_query($params));
$tokenData = json_decode($response, true);
$accessToken = $tokenData['access_token'];
使用access_token发送请求到数据服务接口。例如,获取某站点的访客数和浏览量:
立即学习“PHP免费学习笔记(深入)”;
$siteId = 'your_site_id'; // 在百度统计后台查看
$startDate = '2024-04-01';
$endDate = '2024-04-30';
$dataUrl = "https://openapi.baidu.com/rest/2.0/tongji/report/getData";
$postData = [
'access_token' => $accessToken,
'site_id' => $siteId,
'start_date' => $startDate,
'end_date' => $endDate,
'metrics' => 'pv_count,visitor_count', // 指标:浏览量、访客数
'method' => 'overview/getTimeTrendRpt' // 接口方法
];
$options = [
'http' => [
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($postData)
]
];
$context = stream_context_create($options);
$result = file_get_contents($dataUrl, false, $context);
$data = json_decode($result, true);
// 输出结果
if (isset($data['result'][0]['data'])) {
foreach ($data['result'][0]['data'] as $row) {
echo "日期: {$row['dimension'][0]['name']} ";
echo "PV: {$row['metric'][0]} ";
echo "访客数: {$row['metric'][1]}<br>";
}
}
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号