Last active
March 22, 2023 22:01
-
-
Save dennzo/96c7f1a190a0b04811479817ebeeeca9 to your computer and use it in GitHub Desktop.
PHP - convert woff files from google webfont helper to inline base64 css
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 | |
// I know this is very ugly, but good enough for my use case. | |
// this is highly dependent on fonts from https://gwfh.mranftl.com/fonts/ because of the file names. | |
$files = glob(__DIR__ . '/fonts/*.woff'); | |
foreach ($files as $file) { | |
$baseDirectory = pathinfo($file, PATHINFO_DIRNAME); | |
$fileName = basename($file); | |
$fileNameWithoutExtension = pathinfo($fileName, PATHINFO_FILENAME); | |
$fileExtension = pathinfo($fileName, PATHINFO_EXTENSION); | |
$matches = []; | |
preg_match_all('/^(.*)?-(.*)?-(.*)?-([0-9]{3})?(.*)/m', $fileNameWithoutExtension, $matches); | |
[$fullName, $fontName, $version, $type, $fontWeight, $fontStyle] = $matches; | |
$fontName = ucfirst($fontName[0]); | |
$fontWeight = ($fontWeight[0]) ?: 400; | |
$fontStyle = ($fontStyle[0] === 'italic') ? 'italic': 'normal'; | |
$base64ContentWoff = base64_encode(file_get_contents("$baseDirectory/$fileName")); | |
$base64ContentWoff2 = base64_encode(file_get_contents("$baseDirectory/$fileNameWithoutExtension" . '.woff2')); | |
$res .= <<<CSS | |
@font-face { | |
font-display: swap; /* Check https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display for other options. */ | |
font-family: '{$fontName}'; | |
font-style: {$fontStyle}; | |
font-weight: {$fontWeight}; | |
src: url(data:application/octet-stream;base64,{$base64ContentWoff2}) format('woff2'), | |
url(data:application/octet-stream;base64,{$base64ContentWoff}) format('woff'); | |
} | |
CSS; | |
} | |
file_put_contents(__DIR__ . '/fontfile-with-inline-base64.css', $res ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment