You are here

public function GoogleCSEServices::getAccurateResultsCount in Google Custom Search Engine 8.3

Same name and namespace in other branches
  1. 8.2 src/GoogleCSEServices.php \Drupal\google_cse\GoogleCSEServices::getAccurateResultsCount()

Get the exact (accurate) number of search results to be used in the pager.

Google will never return more than 1000 results for any given search. If a request for the maximum results is made, Google will return the last page of the search results with the start and end position as attributes of the results. The <RES> tag encapsulates the set of individual search results and details about those results. The tag attributes are SN (the 1-based index of the first search result returned in this result set) and EN (the 1-based index of the last search result).

Parameters

string $keys: The search keys.

int $total: The initial estimated total.

Return value

int The accurate total number of results.

1 call to GoogleCSEServices::getAccurateResultsCount()
GoogleCSEServices::responseResults in src/GoogleCSEServices.php
Function to fetch the results xml from Google.

File

src/GoogleCSEServices.php, line 435

Class

GoogleCSEServices
Additional functions as services for Google CSE.

Namespace

Drupal\google_cse

Code

public function getAccurateResultsCount($keys, $total) {
  $total_num_results = 0;

  // Allow other modules to alter the keys.
  $this->moduleHandler
    ->alter('google_cse_searched_keys', $keys);
  $offset = self::GOOGLE_MAX_SEARCH_RESULTS - $this->CSEconfig
    ->get('configuration')['google_cse_adv_results_per_page'];
  $response = $this
    ->service($keys, $offset);
  $xml = simplexml_load_string($response[0]);
  if (isset($xml->RES)) {

    // Get the 1-based index of the last search result item from the result
    // end attribute (EN) of the search result tag (RES).
    $attributes = $xml->RES
      ->attributes();
    $total_num_results += (int) $attributes['EN'];
  }

  // If we do not find an accurate result we will use the initial estimate.
  if (!$total_num_results) {
    $total_num_results = $total;
  }
  return $total_num_results;
}