Mohit Chandel
Mohit Chandel

Reputation: 1916

How to use Page Speed Insight API in localhost with PHP?

Hi I am trying to get the page speed insights using google speed insights API in PHP

$api = 'API KEY';
$url = 'https://www.stackoverflow.com/';
$url_sh = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=".$url."&key=".$api;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url_sh);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result, true));

But getting NULL value as a result

I also tried json_decode but getting the same output

Upvotes: 0

Views: 1723

Answers (2)

Clinton
Clinton

Reputation: 1196

Despite the 'Google Get Started' documentation advising the use of the domain:

https://www.googleapis.com/pagespeedonline/v5/runPagespeed

for page speed insights, I find that the url:

https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed

is more reliable for runPageSpeed.

I use the cURL options shown below to run Page Speed Insights:

$api = 'API KEY';
$url = 'https://www.stackoverflow.com/';
$url_sh = "http://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=".$url."&key=".$api;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURL_TIMEOUT, 200);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL,$url_sh);
$result=curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result, true));

CURLOPT_SSL_VERIFYPEER option set to 0 is essential for the code to run.

Upvotes: 0

GrahamTheDev
GrahamTheDev

Reputation: 24865

The version 1 api was deprecated a loooong time ago, the latest version is version 5, so you just need to change your url to

https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=".$url."&key=".$api;

You can read the getting started documents here

Upvotes: 2

Related Questions