Google PageSpeed ​​Insights API Screenshot

I am trying to extract a screenshot from the API, but when I decode the image and save it, I get a broken image. Below is the code I'm using. I created tinyurl for a sample file containing google response if you want to test it.

$name = 'test';
$result = file_get_contents('http://tinyurl.com/q4smyod'); 
$result = json_decode($result, true);
$decoded=base64_decode($result['screenshot']['data']);
file_put_contents('img/'.$name.'.jpg',$decoded);
+4
source share
2 answers

As mentioned in my comment, the problem is due to googles encryption error when working with php api. If you have this problem, just use the following replacement functions to fix the encoding.

$data    = str_replace('_','/',$result['screenshot']['data']);
$data    = str_replace('-','+',$data);
$decoded = base64_decode($data);
+14
source

This will help you get closer to your goal. You didn't have a name, and your json_decoding was a little weird:

<?php
     error_reporting(-1);
     ini_set('display_errors', 'On');
     $result = file_get_contents('http://tinyurl.com/q4smyod'); 
     $name = 'test2';
     $result = json_decode($result, true);

     $decoded = base64_encode($result['screenshot']['data']);
     file_put_contents($name.'.jpg',$decoded);

?>
0
source

All Articles