Skip to content

Instantly share code, notes, and snippets.

@WebBamboo
Last active June 19, 2020 09:06
Show Gist options
  • Save WebBamboo/80b71ec3d05767b715c08f9320264f3d to your computer and use it in GitHub Desktop.
Save WebBamboo/80b71ec3d05767b715c08f9320264f3d to your computer and use it in GitHub Desktop.
Pagespeed Insights Checker in PHP
<?php
/**
* @author: Pavel Petrov
* Pagespeed Insights API wrapper for PHP
* Article: https://codingstories.net/what-is-google-pagespeed-and-why-does-it-matter
*/
class PagespeedChecker {
private $apiKey = false;
private $url = '';
private $pagespeed;
public function __construct($apiKey=false)
{
if($apiKey)
{
$this->apiKey = $apiKey;
}
}
public function check($url)
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new Exception("Invalid url");
}
$apiUrl = sprintf("https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=%s%s", $url, $this->apiKey ? "&key=".$this->apiKey : '');
$rawResponse = file_get_contents($apiUrl);
$this->pagespeed = json_decode($rawResponse);
return $this;
}
public function getFullResponse()
{
if(is_null($this->pagespeed)) throw new Exception("Empty response. Have you run the check function?");
return $this->pagespeed;
}
public function getScore()
{
try
{
return $this->pagespeed->lighthouseResult->categories->performance->score;
}
catch(Exception $ex)
{
return false;
}
}
}
$checker = (new PagespeedChecker())->check("https://codingstories.net");
var_dump($checker->getScore());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment