1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Display Second Or Random Image From Google Image Search

Discussion in 'PHP' started by ian_batten, Jan 29, 2013.

  1. #1
    Hello,

    I've got the following script which displays the first result from google images, however I'd like it to display either the second or a random image from the specified google image search.

    Anyone know how I can do this?

    This is the script I currently have:

    <?php
     
    $link = "http://images.google.com/images?q=".get_the_title()."&tbm=isch";
    $link = str_replace(' ','_',$link);
    $code = file_get_contents($link,'r');
     
     
    ereg ("imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*", $code, $img);
    ereg ("http://(.*)", $img[0], $img_pic);
     
    $firstImage = $img_pic[0];
    $firstImage = trim("$firstImage");
    echo "";
     
    // Display image
    echo "<a href=\"$firstImage\">
          <img src=\"$firstImage\" class=\"artimage\">
          </a>";
    ?>
    Code (markup):
     
    ian_batten, Jan 29, 2013 IP
  2. ian_batten

    ian_batten Well-Known Member

    Messages:
    1,991
    Likes Received:
    106
    Best Answers:
    0
    Trophy Points:
    185
    #2
    Unfortunately that doesn't work.
     
    ian_batten, Jan 29, 2013 IP
  3. ogah

    ogah Member

    Messages:
    60
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    36
    #3
    function ereg is depracated :)
     
    ogah, Jan 30, 2013 IP
  4. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #4
    use preg_match() instead...


    preg_match("#imgurl=http://www.[A-Za-z0-9-]*.[A-Za-z]*[^.]*.[A-Za-z]*#", $code, $img);
    preg_match("#http://(.*)#", $img[0], $img_pic);
    Code (markup):
     
    Last edited: Jan 30, 2013
    MyVodaFone, Jan 30, 2013 IP
  5. ian_batten

    ian_batten Well-Known Member

    Messages:
    1,991
    Likes Received:
    106
    Best Answers:
    0
    Trophy Points:
    185
    #5
    Thanks for the suggestions, however still doesn't appear to be working.
     
    ian_batten, Jan 30, 2013 IP
  6. firman01

    firman01 Well-Known Member

    Messages:
    155
    Likes Received:
    2
    Best Answers:
    1
    Trophy Points:
    165
    #6
    
     
    // .....
    
    preg_match_all('%imgurl=(http|https)://(.+?)&amp%s', $code, $res, PREG_PATTERN_ORDER);
    if(!empty($res[2])) {
      $res = $res[2];
    
      echo $res[1]."\n"; // im image #2
      echo $res[mt_rand(0,(count($res)-1))]."\n"; // im image #random
    }
    
    Code (markup):
     
    firman01, Feb 2, 2013 IP