PHP script to download MP3 album art from Google Images

847 Views Asked by At

I have a lot of music albums organised into subfolders in the 'My Music' folder in Windows, and finding album art for them is time consuming and cumbersome. I have previously used this little PHP script in my browser to loop through and do a Google Image lookup using the subfolders' names.

$folders = glob('*');

foreach($folders as $folder) {
if(!is_dir($folder)) {
    echo "Skipping {$folder}<br>";
    continue;
}

$searchname = str_replace('_',' ',$folder);

ob_flush();
echo "<b>Checking {$searchname}...</b><br>";
flush();

$googleUrl = "https://www.google.com/search?safe=off&tbm=isch&source=lnt&tbs=isz:l&q=".urlencode($searchname);
$contents = file_get_contents($googleUrl);
$doc = new DOMDocument();
$doc->loadHTML($contents);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
    $counter;
    $tag = $tag->getAttribute('href');
    $tag = parse_url($tag);
    $tag = $tag['query'];

    if ((strpos($tag, "imgurl") !== false) && ($counter < 5)) {
        $counter++;
        preg_match('~=(.*?)&imgrefurl~', $tag, $output);
        $tag = $output[1];
        $image = file_get_contents($tag);

        echo "Downloading image" . $counter . ".jpg<br>";
        file_put_contents("{$folder}/image" . $counter .".jpg", $image);
    }
}
$counter = 0;
}

If I do a var_dump($contents), I can see a Google images DOM after being parsed, but it does not contain any img src links anymore when inspected with Chrome's Dev tools. It now looks visually very different from Google Images' current look.

This got the job done well enough only a couple of months ago, but returning to it now, something broke, maybe because something changed on Google's end.

I am pretty new to coding, so any fixes/comments/alternatives are appreciated to get this working again.

0

There are 0 best solutions below