X
    Categories: PHP

google image search api php

google image search api php

By using the Google API we can return image results in AJAX, we can able to return images for a specific query and then output them in to HTML page.
Below are the simple example using php

PHP code

function get_url_contents($url) {
$crl = curl_init();

curl_setopt($crl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($crl, CURLOPT_URL, $url);
curl_setopt($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 5);

$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}

$json = get_url_contents('http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=sausages');

$data = json_decode($json);

foreach ($data->responseData->results as $result) {
$results[] = array('url' => $result->url, 'alt' => $result->title);
}

print_r($results);

 Output:

Array

(
[0] => Array
(
[url] => http://upload.wikimedia.org/wikipedia/commons/thumb/c/c4/Salchicha_oaxaque%25C3%25B1a.png/220px-Salchicha_oaxaque%25C3%25B1a.png
[alt] => Sausage - Wikipedia, the free encyclopedia
)

[1] => Array
(
[url] => http://upload.wikimedia.org/wikipedia/commons/c/c1/Reunion_sausages_dsc07796.jpg
[alt] => File:Reunion sausages dsc07796.jpg - Wikimedia Commons
)

[2] => Array
(
[url] => http://1.bp.blogspot.com/-zDyoLPoM1Zg/ULXDPba_2iI/AAAAAAAAAAs/QzfNNmDFmzc/s1600/shop_sausages.jpg
[alt] => Maik's Yummy German Sausage
)

[3] => Array
(
[url] => http://sparseuropeansausage.com/images/sausage-web/sausagesBiggrilling2.jpg
[alt] => Spar's European Sausage Shop
)

)


 Showing the images:

<?php foreach($results as $image): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>"/><br/>
<?php endforeach; ?>

 Edit after comments:

$url = 'http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' . get_the_title();

$json = get_url_contents($url);

 

How to GET multiple images?

$images = array("ironman poster", "superman returns poster", "the croods poster", "batman forever poster");

foreach ($images as $i) {
$image = rawurlencode($i);
$query = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".$image."&imgsz=large&as_filetype=jpg";

$json = get_url_contents($query);
$data = json_decode($json);
$results = array(); //define array here!
foreach ($data->responseData->results as $result) {
$results[] = array("url" => $result->url, "alt" => $result->title);
}

echo $results[0]['url'];
echo "<br />";
echo $query;
echo "<br />";
}

Thanks! If you like this article please don’t forget to share and comment.

 

Marimuthu:

View Comments