PHP 获取百度统计数据

180it 2020-10-01 PM 1426℃ 0条
// 账户类型
$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);
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP 获取百度统计数据