I have a page that automatically retrieves two random entries from a MySQL database and asks the user to compare them every time the page is refreshed. How can I convert those two strings into the first google image result for them automatically? This is what I have so far:
<?php //I retrieve the names and group names here//
$firstpersonaName = (string) $row["personaName"];
$firstpersonaGroupName = (string) $row["groupName"];
$firstpersonaGroupNameForGoogle = preg_split('( )', $firstpersonaGroupName);
?> //then convert any group names containing spaces into arrays here//
<?php //then here I build the query that displays a google image page//
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
?>
This gives me stuff like: https://www.google.com/search?q=charlie+always+sunny&tbm=isch
So how do I take that link and turn it into the link of the first image? Or any of the first couple really. (In this case: http://cdn3.denofgeek.us/sites/denofgeekus/files/sunny_0.jpg)
Okay so here's what I ended up doing to randomly generate two pics per query:
First I downloaded this and added it to the same directory as the webpage: http://simplehtmldom.sourceforge.net/
Then I simply added this PHP code in the div where I wanted the picture to show up:
<?php
// Include the php dom parser
include_once 'simple_html_dom.php';
//build the google images query
$newname = '';
foreach ($firstpersonaGroupNameForGoogle as $firstpersonaPartofGroupName) {
$newname = $firstpersonaPartofGroupName . '+';
}
$newname = rtrim($newname, "+");
//echo "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
$newname = "https://www.google.com/search?q=" . $firstpersonaName . "+" . $newname . '&tbm=isch';
//use parser on queried page
$html = file_get_html($newname);
//echo $html;
//create an array for all pics on page
$picarray = array();
$picurl = '';
// Find all images
foreach($html->find('img') as $element) {
//echo $element->src . '<br>';
$picurl = $element->src;
array_push($picarray,$picurl);
}
//then pick two random ones
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
$picurl = $picarray[array_rand($picarray)];
echo "<img src=" . $picurl . ">";
?>
They're pretty small resolution (about 150px) but that actually works great with what I'm trying to do. If you wanted to retrieve a non-thumbnail pic that's a whole different can of worms.