如何修改Google Analytics API代码循环获取过去30天每日访客数据?
Got it, let's walk through exactly how to adjust your existing code to pull daily visitor metrics for the past 30 days. You mentioned three key areas to update, so here's the step-by-step breakdown with concrete code changes:
1. Replace Single Call with a 30-Day Loop
Instead of fetching just the previous day's data once, we'll loop through each of the past 30 days, fetching data for one day at a time. Update your main execution code to this:
// Loop through the past 30 days (adjust $i range if you need a different period) for ($i = 1; $i <= 30; $i++) { // Calculate the target date (e.g., "-1 days" = yesterday, "-2 days" = day before that) $targetDate = date('Y-m-d', strtotime("-{$i} days")); // Pass the specific date to getResults $dailyResults = getResults($analytics, $profile, $targetDate); // Print the results for this individual day printResults($dailyResults, $targetDate); }
2. Update the getResults Function for Single-Day Queries
Modify the Core Reporting API call to use the passed $targetDate as both the start and end date (so we only get data for that specific day). Here's the updated function:
function getResults($analytics, $profileId, $targetDate) { return $analytics->data_ga->get( 'ga:' . $profileId, $targetDate, // Start date: single day $targetDate, // End date: same as start, to isolate daily data 'ga:sessions,ga:users', // Adjust these metrics to match what you need (e.g., ga:pageviews) array( 'dimensions' => 'ga:date', // Include date dimension to verify the day in results 'max-results' => 1 ) ); }
Note: Adjust the metrics (ga:sessions,ga:users) to whatever visitor data you're targeting — just make sure the indices in printResults match later.
3. Modify printResults to Display Daily Context
Update this function to accept and show the target date, so you can clearly see which day's data you're viewing. It should also handle cases where no data exists for a day:
function printResults($results, $targetDate) { // Handle empty data for days with no visitors if (empty($results->getRows())) { echo "* No visitor data found for {$targetDate}\n\n"; return; } // Format and print the daily metrics echo "### Visitor Data for {$targetDate}\n"; echo "- Total Sessions: {$results->getRows()[0][1]}\n"; echo "- Total Users: {$results->getRows()[0][2]}\n\n"; }
Tip: If you added different metrics in getResults, adjust the array indices (e.g., [0][1], [0][2]) to match the order of your metrics.
内容的提问来源于stack exchange,提问作者moi2877

