Last active
August 6, 2018 17:38
-
-
Save gjreasoner/ffcdeea795fbc09ce94adab5bb91eaee to your computer and use it in GitHub Desktop.
Inline GTMetrix Image Optimizer
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 | |
if(!isset($argv[1]) || strlen($argv[1]) < 5){ | |
echo 'usage php optimize.php "https://gtmetrix.com/reports/***YOUR_URL_HERE***/**YOUR_REPORT_ID_HERE**"'; | |
die(); | |
} | |
$full_url = $argv[1]; | |
$domain = strstr(str_replace('https://gtmetrix.com/reports/','',$full_url),'/',true); | |
$content = file_get_contents($full_url); | |
function parseImageLinks($content,$domain){ | |
preg_match_all('/<li>Losslessly compressing <a href="([^"]*)"([^<]*)>([^<]*)<\/a>([^<]*)<a href="([^"]*)"/s',$content,$matches); | |
$images_to_upgrade = $matches[3]; | |
$reduction = $matches[4]; | |
$links_to_images = $matches[5]; | |
$links = []; | |
foreach($images_to_upgrade as $key=>$image_url){ | |
$links[] = [ | |
'url' => "https://gtmetrix.com" . $links_to_images[$key], | |
'path' => str_replace(['https://','http://',$domain.'/'],'',$image_url), | |
'reduction' => trim(str_replace('. See ','',$reduction[$key])) | |
]; | |
} | |
return $links; | |
} | |
function downloadAndReplaceImage($image,$key,$count){ | |
echo "---- $key of $count ----\n"; | |
echo "Getting -> ${image['url']}"; | |
file_put_contents($image['path'], file_get_contents($image['url'])); | |
echo "\Put -> ${image['path']}\n"; | |
echo "\Result -> ${image['reduction']}\n\n"; | |
} | |
$links = parseImageLinks($content,$domain); | |
$count = count($links); | |
foreach($links as $key => $link){ | |
downloadAndReplaceImage($link,$key+1,$count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment