Code Snippet: Updated use of Google suggest for keyword research

In 2010 I posted an article about using Google suggest for keyword research. Google changed some things, so I updated the code to make it working today with some additional optimizations.

Unfortunately Google does not provide the number of search results in the XML anymore, so that there are only the search phrases available. Nevertheless this class could be useful for doing some keyword research, as you will get the most popular search phrases based on your query.

< ?php
  define('SUGGEST_URL', '');
   * Simple class to fetch suggestion data from google. 
   * This could be used for keyword research.
   * @author Martin Albrecht <>
  class gSuggest {
     * Fetch the suggestion data
     * @param string $lang The language identifier (e.g. en, de)
     * @param string $query The query string
     * @throws Exception
    public static function getSuggestData($lang=null, $query=null) {
      // Check parameters 
      if( $lang === null || $query === null ) {
        throw new Exception('Required parameters not set');
      // Create query url
      $queryUrl = str_replace(array('@COUNTRY@', '@QUERY@'), 
                              array($lang, $query), SUGGEST_URL);       
      // Fetch XML from google
      $suggestFeed = file_get_contents($queryUrl);
      if( $suggestFeed === false ) {
        throw new Exception('Cannot load data from query URL');
      // Load XML data into object
      $xmlData = simplexml_load_string(utf8_encode($suggestFeed));
      if( $xmlData === false ) {
        throw new Exception('Cannot load XML data');
      // Process the XML object
      $returnData = array();
      foreach($xmlData->CompleteSuggestion as $element) {
        $s_data = $element->suggestion->attributes();        
        $returnData[] = (string) $s_data['data'];
      return $returnData;

Here’s some example of using this class in which the keyword “javacoffee” is searched on german Google:

  try {
    $data = gSuggest::getSuggestData('de', 'javacoffee');
    foreach($data as $i => $keyword) {
      echo "Keyword ($i): $keyword\n";
  } catch(Exception $e) {
    printf("Error: %s\n", $e->getMessage());

This would a result like:

mbr@malibu:~/Desktop$ php keyword.php 
Keyword (0): javacoffee
Keyword (1): javacoffeebreak
Keyword (2): javacoffeehouse
Keyword (3):
Keyword (4):
Keyword (5):
Keyword (6): java coffee blog
Keyword (7):
Keyword (8):
Keyword (9):

Similar Posts: