Ответ 1
Благодаря @gennadiy за то, что он поставил меня на правильный путь. Без его предложения использовать ->cse->listCse()
для получения результатов, я, вероятно, отказался бы и пошел бы в поисках другой библиотеки. К счастью, это почти все, что мне нужно, чтобы использовать эту библиотеку, поэтому я думаю, что все настроено.
Простой пример
Выполнение поиска довольно просто; он в основном выглядит следующим образом:
include_once __DIR__ . '/vendor/autoload.php';
$GCSE_API_KEY = "nqwkoigrhe893utnih_gibberish_q2ihrgu9qjnr";
$GCSE_SEARCH_ENGINE_ID = "937592689593725455:msi299dkne4de";
$client = new Google_Client();
$client->setApplicationName("My_App");
$client->setDeveloperKey($GCSE_API_KEY);
$service = new Google_Service_Customsearch($client);
$optParams = array("cx"=>self::GCSE_SEARCH_ENGINE_ID);
$results = $service->cse->listCse("lol cats", $optParams);
Объект результатов реализует Iterator, поэтому мы можем перебирать их следующим образом:
foreach($results->getItems() as $k=>$item){
var_dump($item);
}
Предварительные требования Google
Чтобы использовать эту библиотеку, вам нужно сначала создать несколько вещей Google. Эти вещи в конечном итоге упоминаются на веб-сайте API-интерфейсов клиентов API для клиентов Google (Beta), но вам придется щелкнуть и копать для них и даже то вы пропустите последний из них ниже:
- Вам понадобится система пользовательского поиска. Не путайте с тем, что большинство ссылок в Интернете на пользовательские поисковые системы предназначены для людей, которые не пытаются выполнять программные поиски. Вам это нужно, и их легко настроить здесь: https://cse.google.com/cse/all
- Вам понадобится проект Google.. Снова, настроить легко, когда вы знаете, куда идти: https://console.developers.google.com/apis/dashboard
- Вам понадобится ключ API (он же ключ разработчика). Перейдите сюда и создайте новый ключ, если у вас его еще нет: https://console.developers.google.com/apis/credentials
- Вам нужно будет включить Google Custom Search для вашего проекта. На этом этапе вы можете делать запросы в Google, но вы можете получить ответ об ошибке, если вы еще не включили Google Custom Search для ваш проект. Перейдите на панель управления, нажмите синюю ссылку "Включить API", найдите Google Custom Search и включите ее. https://console.developers.google.com/apis/dashboard
Тщательно прокомментированный пример
Это более реалистичный пример, чем приведенный выше пример. Это все еще очень просто, но всегда приятно иметь что-то новое, объясняемое двумя разными способами с большим количеством пояснительных комментариев.
<?php
include_once __DIR__ . '/vendor/autoload.php';
/**
* Retrieves a simple set of google results for a given plant id.
*/
class GoogleResults implements IteratorAggregate {
// Create one or more API keys at https://console.developers.google.com/apis/credentials
const GCSE_API_KEY = "nqwkoigrhe893utnih_gibberish_q2ihrgu9qjnr";
/* The search engine id is specific to each "custom search engine"
* you have configured at https://cse.google.com/cse/all
* Remember that you must have enabled Custom Search API for the project that
* contains your API Key. You can do this at the following url:
* https://console.developers.google.com/apis/api/customsearch.googleapis.com/overview?project=vegfetch-v01&duration=PT1H
* If you fail to enable the Custom Search API before you try to execute a search
* the exception that is thrown will indicate this. */
const GCSE_SEARCH_ENGINE_ID = "937592689593725455:msi299dkne4de";
// Holds the GoogleService for reuse
private $service;
// Holds the optParam for our search engine id
private $optParamSEID;
/**
* Creates a service object for our Google Custom Search. The API key is
* permiently set, but the search engine id may be changed when performing
* searches in case you want to search across multiple pre-prepared engines.
*
* @param string $appName Optional name for this google search
*/
public function __construct($appName = "My_Search") {
$client = new Google_Client();
// application name is an arbitrary name
$client->setApplicationName($appName);
// the developer key is the API Key for a specific google project
$client->setDeveloperKey(self::GCSE_API_KEY);
// create new service
$this->service = new Google_Service_Customsearch($client);
// You must specify a custom search engine. You can do this either by setting
// the element "cx" to the search engine id, or by setting the element "cref"
// to the public url for that search engine.
//
// For a full list of possible params see https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Customsearch/Resource/Cse.php
$this->optParamSEID = array("cx"=>self::GCSE_SEARCH_ENGINE_ID);
}
/**
* A simplistic function to take a search term & search options and return an
* array of results. You may want to
*
* @param string $searchTerm The term you want to search for
* @param array $optParams See: For a full list of possible params see https://github.com/google/google-api-php-client-services/blob/master/src/Google/Service/Customsearch/Resource/Cse.php
* @return array An array of search result items
*/
public function getSearchResults($searchTerm, $optParams = array()){
// return array containing search result items
$items = array();
// Merge our search engine id into the $optParams
// If $optParams already specified a 'cx' element, it will replace our default
$optParams = array_merge($this->optParamSEID, $optParams);
// set search term & params and execute the query
$results = $this->service->cse->listCse($searchTerm, $optParams);
// Since cse inherits from Google_Collections (which implements Iterator)
// we can loop through the results by using `getItems()`
foreach($results->getItems() as $k=>$item){
var_dump($item);
$item[] = $item;
}
return $items;
}
}