Last active
March 30, 2024 23:12
-
-
Save btxtiger/40c8cd6966de9045d44bca59c1d3aa71 to your computer and use it in GitHub Desktop.
Convert Google Fonts embed URL to self-hosted font package
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 | |
/* | |
How to Use: | |
1. Go to GoogleFonts, and save the URL from the font embedding code in a new directory as `gfont-data.css`. | |
2. Save this script in the same directory as `convert.php` | |
3. Run the script via the command line: `php -f convert.php`. | |
4. The script will create a `downloaded` folder, download all fonts into it, and update the CSS file to point to these local copies. | |
5. The updated CSS file will be saved as `fonts.css` in the same directory.t | |
6. Now you can upload it to your site and import it using `@import url(/assets/fonts/fonts.css)`. | |
*/ | |
$cssContent = file_get_contents('gfont-data.css'); | |
preg_match_all('/url\((https:\/\/fonts\.gstatic\.com\/[^)]+)\)/', $cssContent, $matches); | |
$downloadDir = './downloaded'; | |
if (!is_dir($downloadDir)) { | |
mkdir($downloadDir, 0755, true); | |
} | |
foreach ($matches[1] as $url) { | |
$fileName = basename($url); | |
$newFilePath = $downloadDir . '/' . $fileName; | |
file_put_contents($newFilePath, file_get_contents($url)); | |
$cssContent = str_replace($url, $newFilePath, $cssContent); | |
} | |
file_put_contents('fonts.css', $cssContent); | |
echo "Fonts downloaded and CSS file updated."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment