Cache Google Web Fonts Api

in PHP

Google web fonts is a huge library of free web friendly fonts you can easily use on your website. The fonts are loaded in to your website with Javascript and display by using font-family property in your CSS file.

<link href='http://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
font-family: 'Oswald', sans-serif;

There are currently over 650 fonts in the library and they are continuing to add more.

Google has an API developers can use to load the font list into your website, allowing users to select a font to use from accessing the API. All your calls to the Google APIs need to be registered with an API key, you can create your own API keys from the developer console.

Google Developer Console From this screen you can select any Google application and turn on API access for your API key. Search for Web Fonts Developer API and turn this API on.

Google has set a limit of 10,000 requests a day on this API, this is a lot of requests but if you have a popular website it could be used up. So you need to build in a way of caching the response from the API and only making a call when you need to.

The following code will get the results from the Google web font API, store this in a file so we only need to access the API once a week.

/**
 * 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);
    }
}

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To Newsletter

Get weekly updates to your email