How to use PHP client for Google Custom Search Engine

doub1ejack picture doub1ejack · Jan 11, 2017 · Viewed 9.2k times · Source

I'm feeling like this is an idiotic mistake on my part, but I can't figure out how to use the google-api-php-client to do a simple search. My goal is to run simple keyword queries against a google search engine for my site.

I've created my api key, a google search engine and downloaded a release of the api client, but the google site for the php client doesn't seem to have any documentation on how to use the client and the only related example I've found so far specifically searches google's book service. The problem is that example implies that different search services have different search result types and I can't find any documentation on how to retrieve results from a Google_Service.

I think I can set up a simple search like this, but I don't know how to actually retrieve the results.

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

The documentation must be out there, but it's not in any of the obvious places....

Update (1/14/17):

(Update 1/21/17: actually, these docs didn't help me much, but I'll leave them up just FYI)

I used phpdoc to generate api documentation for the google apiclient. I made a repo and put the phpdocs and the libary on github. The phpdocs are browsable here.

So hopefully that will be helpful to someone. Unfortunately even with the docs I'm having trouble unraveling proper usage. I haven't generated docs for the google apiclient-services package yet because they are huge, but I can do that if necessary (depending on disk limits on github pages).

Answer

doub1ejack picture doub1ejack · Jan 22, 2017

Thanks to @gennadiy for putting me on the right track. Without his suggestion to use ->cse->listCse() to retrieve the results, I probably would have given up and gone in search of a different library. Luckily this is pretty much all I need to use this library for so I think I'm all set.

Simple Example

Executing a search is pretty simple; it basically looks like this:

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);

The results object implements Iterator so we can loop over them as follows:

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

Google Prerequisites

In order to use this library though, you will have to set up a few google things first. These things are eventually mentioned on the Google API Client Libraries PHP (Beta) website, but you'll have to click around & dig for them and even then, you'll miss the last one below:

  1. You will need a Custom Search Engine. Don't be confused by the fact that most of the references on the internet to Custom Search Engines are for people who are not trying to do programatic searches. You need one, and they're easy to set up here: https://cse.google.com/cse/all
  2. You will need a Google Project. Again, set up is easy when you know where to go: https://console.developers.google.com/apis/dashboard
  3. You will need an API Key (aka a Developer Key). Go here and create a new key if you don't already have one: https://console.developers.google.com/apis/credentials enter image description here
  4. You will need to enable Google Custom Search for your project. At this point you can make queries to google, but you may get an error response back if you have not yet enabled Google Custom Search for your project. Go to the dashboard, click the blue "Enable API" link, search for Google Custom Search and enable it. https://console.developers.google.com/apis/dashboard enter image description here

A Thoroughly Commented Example

This is a more realistic example than the example above. It is still very simple, but it's always nice to have something new explained in two different ways with lots of explanatory comments.

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