public function GoogleSiteSearch::GetSearchResults in Google Site Search 6
Same name and namespace in other branches
- 7 includes/GoogleSiteSearch.inc \GoogleSiteSearch::getSearchResults()
Get search results.
Parameters
string $query The search query.:
int $page The page to get results from.:
Return value
array The search results.
Throws
Exception
File
- includes/
GoogleSiteSearch.inc, line 213
Class
- GoogleSiteSearch
- Class for interaction with Google Site Search.
Code
public function GetSearchResults($page = 1) {
// set page
$this->currentPage = $page;
// calculate start postition based on page
$startPos = ($this->currentPage - 1) * $this->pageSize;
if ($this->language) {
$language = "&lr=lang_{$this->language}";
}
else {
$language = NULL;
}
// prepare query parameters for URL assembly
if (count($this->extraParams) > 0) {
$extraParamsQuery = '&' . http_build_query($this->extraParams);
}
else {
$extraParamsQuery = NULL;
}
// fetch results from google
$url_response = drupal_http_request(url(GSS_BASE_URL, array(
'query' => drupal_query_string_encode(array(
'start' => $startPos,
'num' => $this->pageSize,
$language,
'client' => 'google-csbe',
'output' => 'xml_no_dtd',
'cx' => $this->key,
'q' => $this->query,
$extraParamsQuery,
)),
)));
if ($url_response->error) {
return NULL;
}
$results = simplexml_load_string($url_response->data);
if ($results !== FALSE) {
if (!isset($results->RES->M)) {
// no results, return NULL
return NULL;
}
else {
// save total results
$this->totalResults = intval(check_plain((string) $results->RES->M));
// store faceted items in order to use them later in the header
$categories = array();
foreach ($results->Context->Facet as $facet) {
$categories[] = array(
'label' => check_plain((string) $facet->FacetItem->label),
'anchor_text' => check_plain((string) $facet->FacetItem->anchor_text),
);
}
$this->categories = $categories;
// init results array
$arr = array();
// loop results
foreach ($results->RES->R as $result) {
// init result array
$item = array();
$item['title'] = filter_xss((string) $result->T, $this
->GetAllowedTags());
$item['url'] = check_url((string) $result->UE);
$item['description'] = filter_xss((string) $result->S, $this
->GetAllowedTags());
// let's get the image thumbnail - present in PageMap->DataObject['type'] == cse_thumbnail
if (isset($result->PageMap->DataObject)) {
foreach ($result->PageMap->DataObject as $do) {
switch ((string) $do['type']) {
case 'cse_thumbnail':
//we are inside the thumbnail node, lets get the src attribute:
foreach ($do->Attribute as $att) {
switch ((string) $att['name']) {
case 'src':
$item['thumbnail_url'] = check_url((string) $att['value']);
break;
}
}
break;
}
}
}
$arr[] = $item;
}
// return results
return $arr;
}
}
else {
throw new Exception('Could not load search results from Google.');
}
}