Skip to content

Instantly share code, notes, and snippets.

@kolaente
Created November 29, 2021 13:58
Show Gist options
  • Save kolaente/ec71aa6db4cba4fb24cc2788c4b9fa9c to your computer and use it in GitHub Desktop.
Save kolaente/ec71aa6db4cba4fb24cc2788c4b9fa9c to your computer and use it in GitHub Desktop.
Google Fonts downloader
#!/usr/bin/php
<?php
/**
* Usage:
* 1. Save the file undere "download-fonts.php"
* 2. Call it with a google fonts css url as the first parameter like this: "download-fonts.php https://fonts.googleapis.com/css2?family=Amiri:ital@0;1&display=swap"
* 3. It will save all fonts to a newly created fonts folder and output the parsed css file with corrected paths. You can adjust the $fontsFilePrefix variable to change the prefix of the font file in the generated css.
*/
if(!isset($argv[1]) || substr($argv[1], 0, 20) !== 'https://fonts.google') {
echo 'Please provide a valid google fonts url as the first parameter!'."\n";
exit(1);
}
$fontCssUrl = $argv[1];
$fontsCss = file_get_contents($fontCssUrl);
$lines = explode("\n", $fontsCss);
$fontsFilePrefix = '../fonts';
$folder = __DIR__ . '/fonts';
@mkdir($folder);
$finalFontCss = '';
foreach($lines as $line) {
$pathPos = strpos($line, 'https://');
if($pathPos === false) {
$finalFontCss .= $line."\n";
continue;
}
$url = substr($line, $pathPos, strpos($line, ')') - $pathPos);
echo "Downloading file $url...\n";
$parts = explode('/', $url);
$newFilename = $parts[4].'-'.$parts[6];
file_put_contents($folder . '/' . $newFilename, file_get_contents($url));
$finalFontCss .= str_replace($url, $fontsFilePrefix . '/' . $newFilename, $line). "\n";
}
echo $finalFontCss;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment