title: Custom Google Analytics API script is working, but running extremely slow
body: <p>I am working on a project using the Google Analytics API for PHP.</p>
  <p>Here is what I need to do: We have about 320 client websites that we track in our Google Analytics account. We are running into an issue where the Google Analytics code stops tracking (for various reasons) on some sites, and we would like to catch this issue before our clients catch it.</p>
  <p>So, what I would like to accomplish is writing a script that checks all of our client sites within Google Analytics and calls the Reporting API and queries for the number of sessions for the last seven days. If there is no data over the last 7 days, the code is more than likely not tracking properly on the website.</p>
  <p>I have created a new API project in Google and obtained a client email that I have added as a user with view permissions to each of my accounts within Google Analytics. I have a total of 63 accounts in my Google Analytics organized by state (New York Clients, Virginia Clients, Oregon Clients etc) and each of the accounts have multiple sub-accounts/profiles under each for a total of 320.</p>
  <p>I have a script that is working, but it is taking a really long time to run. This script does work, as it gives me each profile in my Google Analytics that hasn’t had data over the last 7 days, but it takes about 65 seconds to run and sometimes I get a timeout error because of how long it is taking to run. I’m certain that this is because of the foreach loops that are making a TON of calls to the API. I feel like if I reduced the number of times I am calling the API, the script would run much faster. However, I’m not sure how I can code my script so that it makes fewer calls to the API.</p>
  <p>Is there any way that I could speed up the script below by making fewer calls to the reporting API? Maybe I am going about this the wrong way and there is a more simple way to do what I want to accomplish?</p>
  <p><strong>Here is my working code currently:</strong></p>
  <pre><code> // Load the Google API PHP Client Library.
   require_once __DIR__ . '/vendor/autoload.php';
   //initialize analytics
   $analytics = initializeAnalytics();
   //an array that I will be using below in the getProfileIds() function
   $ProfileIDWithDomain = array();
   //Calls a function to obtain all of the profile IDs to query against the Core reporting API
   $profiles = getProfileIds($analytics);
   //for each profile in the $ProfileIDWithDomain array query the reporting API to get data over 
   last 7 days:
  
   foreach ($profiles as $key =&gt; $value){
       //$key is profile id $value is domain
       $results = getResults($analytics, $key);
       //print the results
       printResults($results,$key,$value);
   }
  
   function initializeAnalytics()
   {
     // Creates and returns the Analytics Reporting service object.
  
     // Use the developers console and download your service account
     // credentials in JSON format. Place them in this directory or
     // change the key file location if necessary.
     $KEY_FILE_LOCATION = __DIR__ . '/{KEY_FILE}';
  
     // Create and configure a new client object.
     $client = new Google_Client();
     $client-&gt;setApplicationName(&quot;GA Analytics Reporting&quot;);
     $client-&gt;setAuthConfig($KEY_FILE_LOCATION);
     $client-&gt;setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
     $analytics = new Google_Service_Analytics($client);
  
     return $analytics;
   }
  
   function getResults($analytics, $profileId) {
     // Calls the Core Reporting API and queries for the number of sessions
     // for the last seven days.
     return $analytics-&gt;data_ga-&gt;get(
          'ga:' . $profileId,
          '7daysAgo',
          'today',
          'ga:sessions');
   }
  
   function printResults($results, $profile,$domain) {
     // Parses the response from the Core Reporting API and prints
     // the profile name and total sessions.
     if (count($results-&gt;getRows()) &lt; 1) {
       echo &quot;&lt;div class='item'&gt;&quot;;
       print &quot;No results found for $profile, domain name: $domain&quot;;
       echo &quot;&lt;/div&gt;&quot;;
     }
   }
  
   function getProfileIds($analytics) {
  
     // Get the list of accounts for the authorized user.
     $accounts = $analytics-&gt;management_accounts-&gt;listManagementAccounts();
  
     if (count($accounts-&gt;getItems()) &gt; 0) {
       //get all 63 accounts in GA
       $items = $accounts-&gt;getItems();
       //array to store accounts
       $AccountIds = array();
       foreach ($items as $item) {
           //for each of the 63 accounts, store the account ID in an array
           $AccountIds[] = $item-&gt;getId();
       }
       //now for each Account ID, we will obtain the properties
       foreach ($AccountIds as $id){
  
           // Get the list of properties for the authorized user.
           $properties = $analytics-&gt;management_webproperties-&gt;listManagementWebproperties($id);
           //if there are more than on item in the properties list (multuple profiles under it)
           if (count($properties-&gt;getItems()) &gt; 0) {
              $items = $properties-&gt;getItems();
              $i = 0;
              if(count($items) &gt; 1){
              foreach($items as $item){
                    //for each item in the property list, get the id
                    $currentPropertyID = $item-&gt;getId();
                    //list management profiles for the id
                    $profiles = $analytics-&gt;management_profiles-&gt;listManagementProfiles($id, $currentPropertyID);
               if (count($profiles-&gt;getItems()) &gt; 0) {
                    $user = $profiles-&gt;getItems();
                    // Store the ID with an associated URL/domain name
                    $ProfileIDWithDomain[$user[0]-&gt;getId()] = str_replace($removeChar, &quot;&quot;, $items[$i][&quot;websiteUrl&quot;]);
  
                    } else {
                       throw new Exception('No views (profiles) found for this user.');
                    }
                    $i++;
                }
             }
             else{
                //only one item in the properties list
                $currentPropertyID = $items[0]-&gt;getId();
                //list management profiles for the id
                $profiles = $analytics-&gt;management_profiles-&gt;listManagementProfiles($id, $currentPropertyID);
                if (count($profiles-&gt;getItems()) &gt; 0) {
                   $user = $profiles-&gt;getItems();
                   // Store the ID with an associated URL/domain name
                   $ProfileIDWithDomain[$user[0]-&gt;getId()] = str_replace($removeChar, &quot;&quot;, $items[0][&quot;websiteUrl&quot;]);
  
                } else {
                   throw new Exception('No views (profiles) found for this user.');
                }
             }
  
           } else {
             throw new Exception('No properties found for this user.');
           }
       }
     } else {
       throw new Exception('No accounts found for this user.');
     }
     //return an associative array with ID =&gt; URL/Domain name for each profile
     return $ProfileIDWithDomain;
   }
  </code></pre>