How to take a screenshot of a web page through a php script

How to take scrrenshot of a qwebpage through php script

In this article i will let you how to take a screenshot of a web page through a php script. in this example i am using google api to get page information.

Here in this article, we will pass website url in the query string parameter of google page speed api.

And the full script looks like below –

<?php 
  
//website url
$siteURL = "http://www.phpzone.in/";

//call Google PageSpeed Insights API
$googlePagespeedData = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$siteURL&screenshot=true");

//decode json data
$googlePagespeedData = json_decode($googlePagespeedData, true);

//screenshot data
$screenshot = $googlePagespeedData['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot); 

//display screenshot image
echo "<img src=\"data:image/jpeg;base64,".$screenshot."\" />";
  
?> 

We have used file_get_contents method to get content of the page in the form of json. Then parse that data to get the image from content. And at the last displaying image from base64 encoded source.

I hope you have learned this really simple and nice method to take a screenshot of a web page. If you have any confusion please write in the comment box.