Page 1 of 1

Access Google Image Search via PHP and CURL

Posted: Sun Jan 04, 2009 7:31 pm
by tier_one
Hi there.

I have been working on a small tool that uses Google's Image Search API and also thanks to this forum, I was able to get it more or less right in the end. So i figured, least I could do is post my code for other people that might need a working solution in the future. I'm far from being an advanced PHP developer so this is kinda basic, but I guess that can still be interesting.

I would very much appreciate comments about the tool that I put online at http://ladaponte.com/fastimages. I wonder if people other than me think it is handy or whether they don't like how it works differently than Google Images.

The code that I used follows.

Code: Select all

 
  $searchquery = "Whatever";
  
  $url = "http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=". $searchquery;
  // 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, "http://www.mysite.com/");
  $body = curl_exec($ch);
  curl_close($ch);
  
  // now, process the JSON string
  $json = json_decode($body);
  //use var_dump($json); to have a look at the results
  
  for($i=0;$i<1;$i++) {
    $class = $json->responseData->results[$i]->GsearchResultClass;
    $imgwidth = $json->responseData->results[$i]->width;
    $imgheight = $json->responseData->results[$i]->height;
    $location = $json->responseData->results[$i]->unescapedUrl;
    $title = $json->responseData->results[$i]->title;
    $titlenoformat = $json->responseData->results[$i]->titleNoFormatting;
    $homepage = $json->responseData->results[$i]->originalContextUrl;
    $tinyurl = $json->responseData->results[$i]->visibleUrl;
    $descformated = utf8_decode($json->responseData->results[$i]->content);
    $descnoformat = utf8_decode($json->responseData->results[$i]->contentNoFormatting);
  }
What this code does is it sends a search request to Google and puts all the information about the resulting images into variables that are easily used however you want in your website. Very straight forward, but if you don't know too much about it, this can still take a couple of hours to get right.

For more Info about the Google Search API: Click here

Hope someone will find this handy in the future.
Later!