Search code examples
phpjsonimage-processingrenderingsearch-engine

Rendering Images from a Json Result (Google Image API) PHP


I can read image search results from the Google Search API, which are stored in a JSON result, an extract from which is below, showing the first result when searching for "elephant":

Storing the Json in $js: $js = json_decode($data,true);

var_dump the json: var_dump($js);

["items"]=> array(10) 
 { [0]=> array(9) 
 { 
   ["kind"]=> string(19) "customsearch#result" 
   ["title"]=> string(66) "African Elephants, African Elephant Pictures, African Elephant ..." 
   ["htmlTitle"]=> string(94) "African Elephants, African Elephant Pictures, African Elephant ..." 
   ["link"]=> string(105) "http://images.nationalgeographic.com/wpf/media-live/photos/000/004/cache/african-elephant_435_600x450.jpg" 
   ["displayLink"]=> string(30) "animals.nationalgeographic.com" 
   ["snippet"]=> string(62) "African Elephants, African Elephant Pictures, African Elephant" 
   ["htmlSnippet"]=> string(83) "African Elephants, African Elephant Pictures, African Elephant" 
   ["mime"]=> string(10) "image/jpeg" 
   ["image"]=> array(7) 
      { 
      ["contextLink"]=> string(71) "http://animals.nationalgeographic.com/animals/mammals/african-elephant/" 
      ["height"]=> int(450) ["width"]=> int(600) 
      ["byteSize"]=> int(55348) 
      ["thumbnailLink"]=> string(111) "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcT8395mqQZUPd2pxSPO7OEPwmjdp5KqtHCRaKzJgcMW_g5mwcEetosfmKU" ["thumbnailHeight"]=> int(101) 
      ["thumbnailWidth"]=> int(135) 
      } 
 } 

I stored the "items" in an array, and can output the title, link, and description (snippet) using the following code:

$googlearray= $js['items'];

    $z=0;
    foreach ($googlearray as $finallist)
    {
     $z++;

    echo $z.": <a href=\"{$finallist['link']}\"><font color ='blue'>{$finallist['title']}</font></a>".": "."$newline"."$newline".$finallist['snippet'].$newline.$newline;

    }

Is it possible to display the actual images on the webpage, rather than just links to the images?

Thanks guys.


Solution

  • If you want to display the image change the a-tag img-tag and use the link as the src-attribute. So something like <img src=\"{$finallist['link']}\" /> should do the trick if I understood your question right.