【问题标题】:How to use PHP client for Google Custom Search Engine如何将 PHP 客户端用于 Google 自定义搜索引擎
【发布时间】:2017-01-11 13:28:42
【问题描述】:

我觉得这是我的一个愚蠢的错误,但我不知道如何使用google-api-php-client 进行简单的搜索。我的目标是针对我的网站的谷歌搜索引擎运行简单的关键字查询。

我已经创建了我的 api 密钥、谷歌搜索引擎并下载了 api 客户端的版本,但 the google site for the php client 似乎没有任何关于如何使用客户端的文档,而 only related example 我已经到目前为止发现专门搜索谷歌的图书服务。问题是该示例意味着不同的搜索服务具有不同的搜索结果类型,我找不到任何有关如何从 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->???

文档必须在外面,但不在任何明显的地方......

更新(17 年 1 月 14 日):

(2017 年 1 月 21 日更新:实际上,这些文档对我没有多大帮助,但我会留下它们,仅供参考)

我使用 phpdoc 为 google apiclient 生成 api 文档。我做了一个回购并把the phpdocs and the libary on github。 phpdocs are browsable here。

希望这对某人有所帮助。不幸的是,即使有这些文档,我也无法解开正确的用法。我还没有为 google apiclient-services 包生成文档,因为它们非常巨大,但如果有必要我可以这样做(取决于 github 页面上的磁盘限制)。

【问题讨论】:

    标签: php api google-custom-search client-library


    【解决方案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);
    

    结果对象实现了迭代器,因此我们可以按如下方式循环它们:

    foreach($results->getItems() as $k=>$item){
        var_dump($item);
    }
    

    Google 先决条件

    不过,为了使用这个库,您必须先设置一些 google 的东西。这些东西最终在Google API Client Libraries PHP (Beta) 网站上被提及,但你必须点击并挖掘它们,即便如此,你也会错过下面的最后一个:

    1. 您将需要一个自定义搜索引擎。不要被互联网上大多数对自定义搜索引擎的引用所迷惑,他们进行程序化搜索。你需要一个,它们很容易在这里设置:https://cse.google.com/cse/all
    2. 您将需要一个 Google 项目。 同样,当您知道去哪里时,设置很容易:https://console.developers.google.com/apis/dashboard
    3. 您将需要一个 API 密钥(也称为开发人员密钥)。如果您还没有,请转到此处并创建一个新密钥:https://console.developers.google.com/apis/credentials
    4. 您需要为您的项目启用 Google 自定义搜索。 此时您可以向 google 查询,但如果您尚未为您的项目启用 Google 自定义搜索,您可能会收到错误响应。转到仪表板,单击蓝色的“启用 API”链接,搜索 Google 自定义搜索并启用它。 https://console.developers.google.com/apis/dashboard

    一个完整注释的例子

    这是一个比上面的例子更现实的例子。它仍然很简单,但是用两种不同的方式用大量的解释性 cmets 来解释一些新的东西总是很好的。

    <?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;
      }
    }
    

    【讨论】:

    • 那么,如果我提供了正确的解决方案,您为什么要自己分配“正确”的答案?
    • 你的解释很好,但@GennadiyLitvinyuk 值得一提。
    • @double1ejack 你必须为谷歌自定义搜索添加站点地图吗?
    【解决方案2】:

    你不能使用Google_Service,而是Google_Service_Customsearch

    $service = new Google_Service_Customsearch($client);
    

    然后:

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

    【讨论】:

    • 太棒了,我明天早上试试。您是如何知道如何从$service 获得结果的?我在the Google_Service client api that I generated 中没有看到任何提示...
    • 我已经阅读了书籍的示例,然后阅读了 Google_Service_Customsearch 和 Google_Service_Customsearch_Resource_Cse 的来源
    【解决方案3】:

    listCse() 函数(现在)只接受一个参数 - API 文档 (https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list) 中提到的完整键数组。

    所以 - 至少 cx 和 q 键必须包含在数组中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-07
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多