PHP Classes

PHP Tutorial on Developing Applications using the Official Google Search API

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Tutorial on Devel...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)  

Author:

Viewers: 1,780

Last month viewers: 1

Categories: PHP Tutorials

Google can provide valuable information on how to find how your site is ranking for important keywords but the right way to do from a Web application is to use official Google Search API instead of scrapping Google search results, which is a practice blocked by Google.

In the first part of this article we learned how to use the PHP Google Custom Search API package to search using the official Google API.

Read this article to learn how to configure more advanced options, as well build a simple search application using this package.




Loaded Article
Picture of Ash Kiswany
By Ash Kiswany Palestine

<email contact>

Introduction

In the first part of the article I talked about how Google is a search expert and how its custom search API engine can provide a quality results like the you can obtain as human user.

Using the PHP Google Custom Search API class and a few PHP loops and array searching you can get very good analysis information to find out where are your golden keywords hiding.

In this article I talk about some more advanced ways to search using the Google search API. Then I will show a simple application demonstrating how everything can be connected together. So let me begin.

More Advanced Example

As I said before, using PHP Google Custom Search API class you can perform a search by passing in the query words plus an optional array of advanced search options to your URL and get a response in JSON or ATOM formats. Now I will show how to do the optional array of search options:

<?php 
use Fogg\Google\CustomSearch\ CustomSearch; 
require 'CustomSearch.php'; 

//Initialize the search class 
$cs = new CustomSearch(); 

//Perform a search with extra parameters
$response = $cs->search('whole foods', ['excludeTerms' => 'tomato']); 

//Perform a search with extra parameters
$response2 = $cs->search('whole foods', ['rights' => 'cc_publicdomain']); 

//Perform a search with extra parameters
$response3 = $cs->search('whole foods', ['dateRestrict' => '25.06.2011']); 

//Perform a search with extra parameters 
$response4 = $cs->search('whole foods', ['lr' => 'lang_ja']);

//Perform a search with extra parameters 
$response5 = $cs->search('whole foods', ['searchType' => 'image']); 

//Perform a search with extra parameters 
$response6 = $cs->search( 'whole foods', ['dateRestrict' => '25.06.2011', 'searchType' => 'image', 'rights' => 'cc_publicdomain']); 

First we specify the namespace we are using to include our class. Then we will initialize the search class. This must be done for every of these examples above.

In the first example we will search for the string "whole foods". In the options parameters we will provide an option called 'excludeTerms' and pass the string 'tomato'.

As you can figure out, we want to get all the results that do not contain the 'tomato' keyword. That can be used to exclude terms we do not need from our search. For passing more than one keyword, we just append the others separating them with commas.

Next again we will search for the terms 'whole foods', but now we will filter by the option 'rights' and give it the choice 'cc_publicdomain'. In this case we are requesting all the search results of content with a public domain license and is about whole foods.

The third example also will search for 'whole foods', but now we will pass the option 'dateRestrict' and value '25.06.2011'. This one means we are collection all search results that are published exactly in 25.06.2011. This is useful if we are looking for some news published in a specific date.

The fourth example concerns the language in which the results are written in. So again for 'whole foods' we use the option 'lr' for specifying language, and lets say we will use 'lang_ja' for Japanese. That is how we will look only for results in Japanese. If your site is in a specific language you can use that for testing it against competitor sites that use that language only.

Let us say you are not looking for text or URL, but you are looking for an image in your site. We can set the search type. So again for 'whole foods', we set the 'searchType' option to 'image'.

Finally, I showed you couple of options, but we can also combine them easily. So as you can see above, the options are provided as an array so we can expand our array and provide more than one option to take in matter at the same search. For the rest of the options here is a table that already presented in the first article.

Table of search options

Parameter nameValueDescription
qstringThe search expression
c2coffstringEnables or disables Simplified and Traditional Chinese Search.
crstringRestricts search results to documents originating in a particular country.
crefstringThe URL of a linked custom search engine specification to use for this request.
cxstringThe custom search engine ID to use for this request.
dateRestrictstringRestricts results to URLs based on date.
exactTermsstringIdentifies a phrase that all documents in the search results must contain.
excludeTermsstringIdentifies a word or phrase that should not appear in any documents in the search results.
fileTypestringRestricts results to files of a specified extension.
filterstringControls turning on or off the duplicate content filter.
glstringGeolocation of end user.
googlehoststringThe local Google domain (for example, google.com, google.de, or google.fr) to use to perform the search.
highRangestringSpecifies the ending value for a search range.
hlstringSets the user interface language.
hqstringAppends the specified query terms to the query, as if they were combined with a logical AND operator.
imgColorTypestringReturns black and white, grayscale, or color images: mono, gray, and color.
imgDominantColorstringReturns images of a specific dominant color.
imgSizestringReturns images of a specified size.
imgTypestringReturns images of a type.
linkSitestringSpecifies that all search results should contain a link to a particular URL
lowRangestringSpecifies the starting value for a search range.
lrstringRestricts the search to documents written in a particular language (e.g., lr=lang_ja).
numunsigned integerNumber of search results to return.
orTermsstringProvides additional search terms to check for in a document, where each document in the search results must contain at least one of the additional search terms.
relatedSitestringSpecifies that all search results should be pages that are related to the specified URL.
rightsstringFilters based on licensing. Supported values include: cc_publicdomain, cc_attribute, cc_sharealike, cc_noncommercial, cc_nonderived, and combinations of these.
safestringSearch safety level.
searchTypestringSpecifies the search type: image. If unspecified, results are limited to webpages.
siteSearchstringSpecifies all search results should be pages from a given site.
siteSearchFilterstringControls whether to include or exclude results from the site named in the siteSearch parameter.
sortstringThe sort expression to apply to the results.
startunsigned integerThe index of the first result to return.

A More Application like Example

What is left for me to show you is how to make a small application to do the job. First we create a file named search.html on which we will put our search form.

The form will request the search term, the Web site domain you want to search and the options you want to provide. Options should be entered in separated lines using commas between the option name and the value. There are better ways to request input from the user, but I will keep it simple just for sake of this article.

<html>
 <head></head>
 <body>
  <form action="result.php" method="post">
   Search term: <input type="text" name="searchterm" /><br />
   Website URL: <input type="text" name="myweb" /><br />
   Options: <textarea name="options" cols="45" rows="5"></textarea><br />
   <input type="submit" value="search" />
  </form>
 </body>
</html>

Next I will create a script named result.php that will process the data. First I am catching the posted input values and pass them to the search class. Then I will loop through the results to find the domain we provided. Finally I display the positions in the results.

<?php
 use Fogg\Google\CustomSearch\ CustomSearch; 
 require 'CustomSearch.php'; 

 //Initialize the search class 
 $cs = new CustomSearch(); 

 //Catch our post inputs
 $term = $_POST[ 'searchterm' ];
 $myweb = $_POST['myweb'];
 $options = explode(PHP_EOL, $_POST[ 'options' ]);

 //Reorganize the options
 foreach($options as $opt) {
  $optstring[] = explode(",",$opt);
 }
	
 //Perform a search with extra parameters 
 $response = $cs->search($term, $optstring);
	
 //Loop through the results
 for($i = 0; $i < count($response); $i++) {
  if( $response[$i] == $myweb ) {
   print $i;
   break;
  }
 }
?>

Conclusion

The PHP Google Custom Search API is a class  that allows PHP applications to perform searches using the Google search engine. This class can perform arbitrary searches on Google using their custom search API.

I showed you how to make a simple app to look for your sites position for some keywords, and I showed you some examples of advanced use of this API. Now it should be easier for you to develop more complex application.

This application was simplified for the sake of simplicity. The is idea was to demonstrate how you can implement applications using the information from Google searches.

If you liked this article or have questions about developing applications based on the Google Search API, post a comment here.




You need to be a registered user or login to post a comment

1,616,729 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:



Comments:

3. How to get the actual results... - Hal Sclater (2016-03-29 08:18)
How can I get the actual details in the results of the search?... - 0 replies
Read the whole comment and replies

2. Initial Article - Debbie Schmidt (2016-02-17 21:12)
First article in this series?... - 1 reply
Read the whole comment and replies

1. weather API - krishnpal singh (2016-02-17 21:12)
API... - 1 reply
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP Tutorial on Devel...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)