Last active
April 3, 2020 05:39
-
-
Save LeoBenoist/c7dfec2cf9f2228e3f04d13a5d48f215 to your computer and use it in GitHub Desktop.
Find Image on google
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Inspired by https://github.com/damiankw/google.imagesearch | |
*/ | |
class GoogleImageSearch | |
{ | |
public function findImagesForQuery(string $query): array | |
{ | |
$html = $this->queryGoogle($query); | |
$pattern = '/\bhttps?:\/\/\S+(?:jpg)\b/'; | |
preg_match_all($pattern,$html,$matches); | |
if (!isset($matches[0])) { | |
return null; | |
} | |
return $matches[0]; | |
} | |
public function findImageForQuery(string $query): ?string | |
{ | |
$result = $this->findImagesForQuery($query); | |
if (!isset($result[0])) { | |
return null; | |
} | |
return $result[0]; | |
} | |
protected function queryGoogle(string $query): string | |
{ | |
$httpContext = stream_context_create( | |
[ | |
'http' => [ | |
'method' => "GET", | |
'header' => "Accept: text/html\r\n" . | |
"User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\n", | |
], | |
] | |
); | |
$url = "https://www.google.com/search?q=" . urlencode($query) . "&source=lnms&tbm=isch&biw=1440&bih=770"; | |
return file_get_contents($url, false, $httpContext); | |
} | |
} | |
$list = explode(PHP_EOL, file_get_contents('list')); | |
$result = sprintf('"%s";"%s"%s', 'label', 'image', PHP_EOL); | |
$googleImageSearch = new GoogleImageSearch(); | |
foreach ($list as $key => $query) { | |
echo "Looking for an image for $query. Line number: ".($key + 1).PHP_EOL; | |
$searchResult = $googleImageSearch->findImageForQuery($query); | |
$result .= sprintf('"%s";"%s"%s', $query, $searchResult, PHP_EOL); | |
} | |
file_put_contents('images.csv', $result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment