1. 程式人生 > >PHP獲取百度統計資料

PHP獲取百度統計資料

// 賬戶型別
$tye 		= 1;
// 站點ID,可以提供位址列拿到
$siteId     = 12169310;
// 使用者名稱
$username   = 'hongfs';
// 密碼
$password   = 'xxxxxxxx';
// Token 獲取方式:https://tongji.baidu.com/web/help/article?id=129&type=0
$toekn      = 'dfdb991d49455b4f6b4a53433f045a18';

/*
 * 獲取資料
 * 
 * @param int $day 查詢天數
 * @return array|boolean
 */
function
getData($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); }