Skip to content

Instantly share code, notes, and snippets.

@samilkorkmaz
Created December 23, 2023 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samilkorkmaz/f7f815afb701bb65d7df795956fe9b74 to your computer and use it in GitHub Desktop.
Save samilkorkmaz/f7f815afb701bb65d7df795956fe9b74 to your computer and use it in GitHub Desktop.
Measure page load time with PHP using Google PageSpeed Insights API
private static function getPageSpeedInsights($url) {
$apiUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
/*$queryParams = http_build_query([
'url' => $url,
'key' => 'YOUR_API_KEY' // If you plan on using the API in an automated way and making multiple queries per second, you'll need an API key
]);*/
$queryParams = http_build_query([
'url' => $url
]);
$ch = curl_init("$apiUrl?$queryParams");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
private static function measurePageLoadTime() {
echo "<h2>TEST measurePageLoadTime</h2>";
$url = "url of website you want to measure";
echo "Started measurePageLoadTime for $url...<br>";
//Display the above message immediately, without waiting for operations to finish:
ob_flush();
flush();
$start_time = microtime(true);
$result = self::getPageSpeedInsights($url);
$end_time = microtime(true);
if (isset($result['lighthouseResult']['audits']['first-contentful-paint']['displayValue'])) {
$fcpValue = $result['lighthouseResult']['audits']['first-contentful-paint']['displayValue'];
echo "First Contentful Paint: $fcpValue";
} else {
echo "First Contentful Paint data not available.";
}
echo "<br>Total time [s]: " . number_format($end_time - $start_time, 2) . "<br>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment