Code to get data from the Google AJAX Search API in PHP

  • 2020-03-31 20:29:41
  • OfStack

(link: http://code.google.com/apis/ajaxsearch/documentation/#fonje)

 
// This example request includes an optional API key which you will need to 
// remove or replace with your own key. 
// Read more about why it's useful to have an API key. 
// The request also includes the userip parameter which provides the end 
// user's IP address. Doing so will help distinguish this legitimate 
// server-side traffic from traffic which doesn't come from an end-user. 
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" 
. "q=Paris%20Hilton&key=INSERT-YOUR-KEY&userip=USERS-IP-ADDRESS"; 

// sendRequest 
// note how referer is set manually 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_REFERER, ); 
$body = curl_exec($ch); 
curl_close($ch); 

// now, process the JSON string 
$json = json_decode($body); 
// now have some fun with the results... 

API KEY application address:
(link: http://code.google.com/apis/ajaxsearch/signup.html)

So we can write a function that looks like this
 
function google_search_api($args, $referer = '//www.jb51.net/', $endpoint = 'web'){ 
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint; 
if ( !array_key_exists('v', $args) ) 
$args['v'] = '1.0'; 
$url .= '?'.http_build_query($args, '', '&'); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_REFERER, $referer); 
$body = curl_exec($ch); 
curl_close($ch); 
return json_decode($body); 
} 

//Use the sample
$rez = google_search_api(array( 
'q' => '21andy.com', //queries
'key' => ' You got it API KEY', 
'userip' => ' your IP address ', 
)); 
header('Content-type: text/html; charset=utf-8;'); 
echo '<xmp>'; 
print_r($rez); 
echo '</xmp>'; 


Related articles: