Skip to content

PHP – Cache Google Web Fonts using Api

/**
 * Get google fonts
 *
 * @param  integer $amount - Return a chuck of fonts
 *
 * @return Array of fonts
 */
function get_google_fonts( $amount = 30 )
{
    $fontFile = '/fonts/google-web-fonts.txt';

    //Total time the file will be cached in seconds, set to a week
    $cachetime = 86400 * 7;

    if(file_exists($fontFile) && $cachetime < filemtime($fontFile))
    {
        $content = json_decode(file_get_contents($fontFile));
    } else {
        $googleApi = 'https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key={API_KEY}';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $googleApi);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $fontContent = curl_exec($ch);
        curl_close($ch);

        $fp = fopen($fontFile, 'w');
        fwrite($fp, $fontContent);
        fclose($fp);

        $content = json_decode($fontContent);
    }

    if($amount == 'all')
    {
        return $content->items;
    } else {
        return array_slice($content->items, 0, $amount);
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments