PHP 获取百度统计数据

PHP 获取百度统计数据

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
// 账户类型
$tye = 1;
// 站点ID,可以提供地址栏拿到
$siteId = 12169310;
// 用户名
$username = 'hongfs';
// 密码
$password = 'xxxxxxxx';
// Token 获取方式:https://tongji.baidu.com/web/help/article?id=129&type=0
$toekn = 'dfdb991d49455xx16b4a53433f045a18';

/*
* 获取数据
*
* @param int $day 查询天数
* @return array|boolean
*/
function getData(int $day = 7) {
$day--;

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://api.baidu.com/json/tongji/v1/ReportService/getData');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
'Content-Type: application/json' // 防止无法接收CURLOPT_POSTFIELDS内容
]);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode([
'header' => [
'account_type' => $type,
'username' => $username,
'password' => $password,
'token' => $toekn,
],
'body' => [
'siteId' => $siteId,
'method' => 'overview/getTimeTrendRpt',
'start_date' => date('Y-m-d', strtotime("-" . $day . " day")),
'end_date' => date('Y-m-d'),
'metrics' => 'pv_count,ip_count,visitor_count',
'gran' => 'day',
'max_results' => $day
]
]));
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
if(curl_errno($curl)) {
return false;
}
curl_close($curl);

return json_decode($result, true);
}
往上