Wednesday, September 3, 2014

Using Google PageSpeed Insights API with php

9/03/2014

In this post we learn how to analyze websites using google pagespeed insights api with PHP. First of all you need to acquire an API key: 




1) Go to the Google Developers Console

2) Select a project, or create a new one. 

3) In the sidebar on the left, expand APIs & auth. Next, click APIs. In the list of APIs, make sure the status is ON for the PageSpeed Insights API. 

4) In the sidebar on the left, select Credentials

5) This API supports two types of credentials. You need only Public API access: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

To create an API key, click Create new Key and select the appropriate key type. Enter the additional information required for that key type and click Create.

Replace "API_KEY" with your ones in following php function.


<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

function checkPageSpeed($url){  
  if (function_exists('file_get_contents')) {  
    $result = @file_get_contents($url);  
  }  
  if ($result == '') {  
    $ch = curl_init();  
    $timeout = 60;  
    curl_setopt($ch, CURLOPT_URL, $url);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
    $result = curl_exec($ch);  
    curl_close($ch);  
  }  

  return $result;  
}

?>

HOW TO USE CODE
<?php
/*
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.com/
*/

$myKEY = "API_KEY";
$url = "http://4evertutorials.blogspot.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '
';
print_r(json_decode($results,true)); 
echo '
'; ?>

helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

3 comments:

Unknown said...

This was quite helpful to me in getting Google PageSpeed Insights API to work in PHP. I don't understand one part of the code: in the function checkPageSpeed(), it seems to me that the curl stuff will only run on an empty result. Is this true? What is the purpose of the curl stuff? I don't know anything about curl.

bindashsandeep said...

Thanks for the code dude :) Working like a charm. Cheers!!

Anonymous said...

It works just perfect. Is there any possibility to run the API to get screenshot.width and screenshot.height other than the default of 320px,240px?

 

© 2014 4everTutorials. All rights resevered.

Back To Top