如何使用PHP客户端进行Google自定义搜索引擎?

16
我感觉这是我自己愚蠢的错误,但我无法弄清如何使用google-api-php-client来进行简单搜索。我的目标是针对我的网站,在谷歌搜索引擎上运行简单的关键字查询。
我已经创建了我的API密钥、谷歌搜索引擎并下载了API客户端的版本,但php客户端的谷歌网站似乎没有任何关于如何使用客户端的文档,而且我到目前为止找到的唯一相关示例专门搜索谷歌的图书服务。问题在于该示例表明不同的搜索服务具有不同的搜索结果类型,而我找不到任何有关如何从Google_Service检索结果的文档。
我认为我可以设置一个简单的搜索,但我不知道如何实际检索结果。
include_once __DIR__ . '/vendor/autoload.php';
...
public function __construct($searchTerm) {
    $client = new Google_Client();
    $client->setApplicationName("My_First_Search");
    $client->setDeveloperKey(self::GCSE_API_KEY);
    $service = new Google_Service($client);
    $optParams = array('filter' => $searchTerm);
    $results = $service->???

文档一定存在,但它并不在任何显而易见的地方...

更新(1/14/17)

(更新1/21/17:实际上,这些文档并没有帮助我太多,但我将它们保留仅供参考。)

我使用 phpdoc 生成了 Google apiclient 的 API 文档。 我创建了一个仓库并放置了 phpdocs 和 libary 在 github 上Phpdocs 可在此处浏览。

因此,希望这对某人有所帮助。 不幸的是,即使有文档,我也很难理解正确的用法。 我尚未为 Google apiclient-services 包生成文档,因为它们非常大,但如果需要(取决于 Github 页面上的磁盘限制),我可以这样做。

3个回答

23

感谢@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);
结果对象实现了迭代器,因此我们可以按如下方式循环遍历它们:
foreach($results->getItems() as $k=>$item){
    var_dump($item);
}

谷歌前提条件

为了使用这个库,您需要先设置一些谷歌要素。这些要素最终在Google API Client Libraries PHP (Beta)网站上有提到,但您需要点击并查找它们,即使如此,您仍会错过以下最后一项:

  1. 您需要一个自定义搜索引擎。 不要被互联网上大多数关于自定义搜索引擎的参考所困惑,因为大多数人都不是在尝试进行编程搜索。 您需要一个,您可以在此处轻松设置:https://cse.google.com/cse/all
  2. 您需要一个谷歌项目。 当您知道去哪里时,设置起来很容易:https://console.developers.google.com/apis/dashboard
  3. 您需要一个API密钥(也称为开发者密钥)。 如果您还没有一个,请在此处创建一个新密钥:https://console.developers.google.com/apis/credentials 输入图像描述
  4. 您需要启用项目的Google自定义搜索。 此时,您可以向谷歌发出查询,但如果您尚未为项目启用Google自定义搜索,则可能会收到错误响应。 转到仪表板,单击蓝色的“启用API”链接,在其中搜索Google自定义搜索并启用它。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;
  }
}

2
所以如果我提供了正确的解决方案,为什么您自己将"正确"答案分配给了自己呢? - Gennadiy Litvinyuk
1
你的解释很好,但是@GennadiyLitvinyuk应该得到更高的奖励而不仅仅是一份提及。 - José Carlos PHP
@double1ejack 你需要为 Google 自定义搜索添加站点地图吗? - FerdousTheWebCoder

9

你需要使用的不是Google_Service,而是Google_Service_Customsearch

$service = new Google_Service_Customsearch($client);

然后:
$results = $service->cse->listCse($searchTerm, $optParams);

太棒了,我明天早上会试一下。你是怎么找到从$service获取结果的方法的呢?我在生成的Google_Service客户端API文档中没有看到任何提示... - doub1ejack
我已经阅读了有关书籍的示例,以及Google_Service_CustomsearchGoogle_Service_Customsearch_Resource_Cse的源代码。 - Gennadiy Litvinyuk

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接