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

前端之家收集整理的这篇文章主要介绍了如何使用PHP客户端进行Google自定义搜索引擎前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我感觉到这是我的一个愚蠢的错误,但我不知道如何使用 google-api-php-client做一个简单的搜索.我的目标是针对我的网站的Google搜索引擎运行简单的关键字查询.

我创建了我的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->???

文件必须在那里,但它不是在任何明显的地方….

更新(1/14/17):

(更新1/21/17:实际上,这些文档没有帮助我,但是我会把它们留给FYI)

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

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

感谢@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的东西.这些东西最终在Google API Client Libraries PHP (Beta)网站上提到,但你必须点击&挖掘他们,即使如此,你会错过下面的最后一个:

>您将需要一个自定义搜索引擎.不要因为互联网上大多数引用到自定义搜索引擎的用户都不想做程序搜索的事实而感到困惑.你需要一个,他们很容易在这里设置:https://cse.google.com/cse/all
>您将需要一个Google Project.再一次,当你知道去哪里时,设置很简单:https://console.developers.google.com/apis/dashboard
>您将需要一个API密钥(也称为开发人员密钥).如果您还没有一个,请到这里创建一个新的密钥:https://console.developers.google.com/apis/credentials
>您将需要为您的项目启用Google自定义搜索.此时,您可以向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;
  }
}
原文链接:https://www.f2er.com/php/132907.html

猜你在找的PHP相关文章