MARVICRM.COM

Home / Screenshot a website using PHP

Screenshot a website using PHP

enter image description here


(c) Google

Creating a website screenshot is never been easy. there's a lot of libraries on Github to do such task but would require importing many libraries, configuration..etc..

fortunately Google has this API called PageSpeed API wherein we can use it by just calling the PageSpeed url and btw, no API key required! how cool is that!

once called, this API will return a json data which contains the screenshot image of the target website (base64_encoded text)

To call the API, simply make a GET request to this url

https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=http://google.com&screenshot=true&strategy=desktop

Just replace the "url" with your target website, while the "strategy" parameter has 2 values (desktop|mobile)

default is "desktop"

once the API is called, output should be like this

enter image description here


that's a bunch of base64_encoded data!

to display the actual image we are going to parse the json. on our example i will use PHP

here is the short code

$url = "http://google.com";

$data = json_decode(file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$url&screenshot=true&strategy=desktop"));

// encoded base64 image

$base64_str = $data->screenshot->data;

// replace the returned base64 string

$base64_str = str_replace('_','/',$base64_str);

$base64_str = str_replace('-','+',$base64_str);

// output as jpeg file

header('Content-type: image/jpeg');

$decoded = base64_decode($base64_str);

echo $decoded;

?>

On my code you will see that i replaced some of the strings of the returned base64 data and as been said on the API documentation:

enter image description here


Output (base on the code)

enter image description here


If you'll change the value of "strategy" parameter to "mobile", the output will be like this

enter image description here


One of the limitations of this API is the fixed image size. It's only 320x240 pixels. I hope they update their API in the future to let the developer set the screenshot size.

Okay, that's it! :)