How to take screenshot web page by php through Google PageSpeed Insights API

Authors: CodeToday | PHP Code | Views: 839 | Posted: 08 AM: 09/11/2017

There are many ways to take screenshot a website like using php library, using software installed on your computer, taken from your phone.

Here I will show you how to screen a website using php and the Google PageSpeed Insights API

The Google PageSpeed Insights API provides us with a lot of site stats like Speed, pageStats (html, css) .. and the screen of the website in json format. 

Google PageSpeed Insights API URL:[ website url ]&screenshot=true

In this article we use the following knowledge

  1. curl_init(): Get data from google API
  2. json_decode(): Takes a JSON encoded string and converts it into a Array PHP


Submit form url you can see in the previous post

PHP Source Code

$url = '';
echo '<pre>'.$url.'</pre>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPGET, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION , 1 );
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_REFERER, $ref );
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);     
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$data = curl_exec($ch);

$result = json_decode($data,true);
$score  = $result['ruleGroups']['SPEED']['score'];
$img    = str_replace('_','/',str_replace('-','+',$result['screenshot']['data']));
echo '<h3>Desktop Friendly Score: </strong>'.$score.'/100</strong></h3>';
echo '<img src = "data:image/jpeg;base64,'.$img.'">';
The example above is the website and takes two parameters: score and screenshot. After performing the above steps the result will be as shown below

How to take screenshot web page by php through Google PageSpeed Insights API

In addition, you can check the compatibility and screenshot of a website url on the mobile device by query:[ website url ]&screenshot=true&strategy=mobile

Note: if you want to check direct website url on Google PageSpeed Insights

If you have any questions, please leave a message below