Get First Google Image Search Result with PHP
Saturday, August 13th, 2011Here’s a quick & dirty way to get the thumbnail image for the first search result in Google Image Search:
<?php
if(isset($_GET['q'])){
$q = urlencode($_GET['q']);
$jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q; $result = json_decode(file_get_contents($jsonurl), true); header("Content-Type: image/jpg"); $img = imagecreatefromjpeg($result['responseData']['results'][0]['tbUrl']); imagejpeg($img); imagedestroy($img);
exit;}
?>
<html>
<body>
<form action='' method='post'>
<fieldset>
<input type='text' name='q' /><input type='submit' name='submit' />
</fieldset>
</form>
<?php
if(isset($_POST['q'])){
$q = urlencode($_POST['q']); $jsonurl = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$q; $result = json_decode(file_get_contents($jsonurl), true); echo "<img src='{$result['responseData']['results'][0]['tbUrl']}' />";
}
?>
</body>
</html>
A few notes:
- Your PHP install must have gd which it probably will if you’re running 5+ which is required for
json_decode(the functionfile_get_contentsis 5.2+, but is just a shorthand function.) - For my purposes I only needed a thumbnail-sized image, but Google’s API provides piles of useful data. View the data directly [example], and copy+paste into a parser [example] if you need help navigating the data structure they provide. PHP’s
json_decodewill turn Google’s JSON data object into a deeply-nested array (and using “true” for the optional second parameter will make it an associative array which is helpful. - When you access the script by URL with the
'q'variable set the image itself will be served, which I needed for my pipeline. This way I was able to call the script in the HTML itself via:<img src='firstgoogleimage.php?q=figgalicous' />which as of this writing serves:
- You can try it yourself here: http://mikefigueroa.com/code/firstgoogleimage.php


