Simple Search Interface


Presenting a simple search interface requires only a small amount of code, and it turns the previous hard-coded example into your own personal Google. To simplify this (and future) examples, the process of constructing a query has been moved into its own function:

 function runGoogleSearch($client, $searchQuery, $start) {    $query = array(       'key'=>'u6U/r39QFHK18Qcjz/XdWSbptVaj9k1t',       'q'=>$searchQuery,       'start'=>$start,       'maxResults'=>10,       'filter'=>true,       'restrict'=>'',       'safeSearch'=>true,       'lr'=>'',       'ie'=>'',       'oe'=>''   );   $result = $client->call("doGoogleSearch", $query, "urn:GoogleSearch", "urn:GoogleSearch");   return $result; } 

This function performs the same basic search as shown in the previous example; really nothing new to see here. I haven't included any of the other attributes in the parameter list for this function to keep things simple. If you need them, feel free to add them. The two places you will most often see the Google API at work are templated search results for a small corporate website, and an automated process to monitor keywords. In the first case you generally want to present as few options as possible (to reduce confusion, and save on screen real estate), and in the second, all of the required options are generally known ahead of time.

 <html> <head> <title>Simple Search Interface</title> </head> <body> <form action=""method="get"> <input type="hidden" name="start" value="0"> <input type="text" name="query" value=""> <input type="submit"> </form> <br> <?php 

This is just your basic HTML form — the hidden variable will be sent to Google to indicate the desired first result. It doesn't do anything here, but when you request the second set of results it will be incremented. I have used a GET variable (rather than POST) here for two main reasons: It is the same method Google uses on its search page, and it will assist in easy transfer from one page to another when paging through the results.

 if (isset($_GET['query'])) { 

The code to execute the API call will only be executed if you do in fact have a query to run. This is something to keep in mind because you are only given 1,000 queries per day to play with.

   require('../lib/nusoap.php');   $searchQuery = $_GET['query'];   $start = $_GET['start']; 

The information from the two GET variables passed from the form are assigned to their own variables. Though no actual filtering is performed here, it is good practice to never use $_GET or $_POST in a function call not directly related to filtering the data. Data filtering is implemented in the next example.

   $client = new soapclient("http://example.org/googleapi/GoogleSearch.wsdl", true);   if ($client->getError())   {     echo "Error creating client <pre>" . $client->getError() . "</pre>";     exit;   }   $client->soap_defencoding = 'UTF-8'; 

Here you check to ensure that the client object was created successfully. You might hit errors at this point if the WSDL file specified in the creation of the object is invalid or unreachable. It is far better to catch things like this now, gracefully, than later when other elements start breaking.

   $result = runGoogleSearch(&$client, $searchQuery, $start); 

The results are obtained from the new function declared previously. Notice the use of the ampersand before $client; this is to ensure the object is passed by reference rather than by value. This way if the $client object raises an error, you will be able to check for it later.

   if ($client->fault)   {     echo 'Client Fault<pre>';     print_r($result);     echo '</pre>'; 

The promised error checking is performed. A client fault is an error handled in the SOAP protocol. There are four acceptable fault codes:

  • Server — Something bad happened on the side of the server. It isn't your fault, and generally if you wait, this will resolve itself (this occurred during writing, and it resolved itself in a few hours).

  • Client — For some reason the server didn't understand your request. Check your code again and try again.

  • VersionMismatch — This happens when the version of SOAP declared in the envelope doesn't match something the server can understand or provide (allows for graceful failures with newer versions).

  • MustUnderstand — These errors occur when a header entry includes a MustUnderstand=1 attribute, but the server does not in fact understand the entry. Check the specification for the feed and try again.

   } else {     if ($client->getError())    {     echo 'Error<pre>' . $client->getError() . '</pre>'; 

A client error encountered here is an error of a different sort. Something went wrong in interpreting the results (for example, if Google returned a malformed SOAP response body) and the appropriate response object couldn't be created.

    } else    {      echo "<b>Search Query</b>: <i>" . $result['searchQuery'] . "</i><br>";      $x = $result['startIndex'];      $y = $result['endIndex'];      if ($result['estimateIsExact'])      {        echo "Displaying results $x to $y, out of ".          $result['estimatedTotalResultsCount'] . "results<br>";      }else      {        echo "Displaying results $x to $y, out of an estimated ".          $result['estimatedTotalResultsCount'] . " results<br>";      }      $queryResults = $result['resultElements'];      foreach($queryResults as $item)      {        echo "<a href=\"{$item['URL']}\">{$item['title']}</a><br>";        echo $item['snippet'] . "<br><br>";      }      $nextStart = $result['endIndex'];      echo "<br><br>";      echo "<a href=\"./nusoap.simple.php?query=$searchQuery&start=$nextStart\">Next        10 Results</a>";    }   } } </body></html> 

Finally, the results are printed out in some semblance of an attractive manner. Notice the last two echo statements near the end — they produce a link to allow the user to select the next 10 results. Performing a simple search for my name with this interface gives you something like that shown in Figure 6-2.

image from book
Figure 6-2




Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
Professional Web APIs with PHP. eBay, Google, PayPal, Amazon, FedEx, Plus Web Feeds
ISBN: 764589547
EAN: N/A
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net