Last active
June 19, 2020 09:06
-
-
Save WebBamboo/80b71ec3d05767b715c08f9320264f3d to your computer and use it in GitHub Desktop.
Pagespeed Insights Checker in PHP
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 | |
/** | |
* @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