External URL Screenshot Using PHP And Pagespeedapi

In this post we discussing about how to take screenshot using php and for that we are going to using google pagespeedapi  .

Google PageSeed API Is Free and it can be obtained via Google. No need of google account before you started .

So lets take look at API

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

Request Parameter:
url : String

Response:

{
  "captchaResult": string,
  "kind": "pagespeedonline#result",
  "id": string,
  "loadingExperience": {
    "id": string,
    "metrics": {
      (key): {
        "percentile": integer,
        "distributions": [
          {
            "min": integer,
            "max": integer,
            "proportion": double
          }
        ],
        "category": string
      }
    },
    "overall_category": string,
    "initial_url": string
  },
  "originLoadingExperience": {
    "id": string,
    "metrics": {
      (key): {
        "percentile": integer,
        "distributions": [
          {
            "min": integer,
            "max": integer,
            "proportion": double
          }
        ],
        "category": string
      }
    },
    "overall_category": string,
    "initial_url": string
  },
  "lighthouseResult": {
    "requestedUrl": string,
    "finalUrl": string,
    "lighthouseVersion": string,
    "userAgent": string,
    "fetchTime": string,
    "environment": {
      "networkUserAgent": string,
      "hostUserAgent": string,
      "benchmarkIndex": double
    },
    "runWarnings": [
      (value)
    ],
    "configSettings": {
      "emulatedFormFactor": string,
      "locale": string,
      "onlyCategories": (value),
      "onlyCategories": (value)
    },
    "audits": {
      (key): {
        "id": string,
        "title": string,
        "description": string,
        "score": (value),
        "score": (value),
        "scoreDisplayMode": string,
        "displayValue": string,
        "explanation": string,
        "errorMessage": string,
        "warnings": (value),
        "warnings": (value),
        "details": {
          (key): (value)
        }
      }
    },
    "categories": {
      (key): {
        "id": string,
        "title": string,
        "description": string,
        "score": (value),
        "score": (value),
        "manualDescription": string,
        "auditRefs": [
          {
            "id": string,
            "weight": double,
            "group": string
          }
        ]
      }
    },
    "categoryGroups": {
      (key): {
        "title": string,
        "description": string
      }
    },
    "runtimeError": {
      "code": string,
      "message": string
    },
    "timing": {
      "total": double
    },
    "i18n": {
      "rendererFormattedStrings": {
        "varianceDisclaimer": string,
        "opportunityResourceColumnLabel": string,
        "opportunitySavingsColumnLabel": string,
        "errorMissingAuditInfo": string,
        "errorLabel": string,
        "warningHeader": string,
        "auditGroupExpandTooltip": string,
        "passedAuditsGroupTitle": string,
        "notApplicableAuditsGroupTitle": string,
        "manualAuditsGroupTitle": string,
        "toplevelWarningsMessage": string,
        "scorescaleLabel": string,
        "crcLongestDurationLabel": string,
        "crcInitialNavigation": string,
        "lsPerformanceCategoryDescription": string,
        "labDataTitle": string
      }
    }
  },
  "analysisUTCTimestamp": string,
  "version": {
    "major": integer,
    "minor": integer
  }
}

Demo Code PHP Script:

<?php
$screenshot_image="";
if(!empty($_POST['url']))
{

    $url =$_POST['url'];
    $url="https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=$url&screenshot=true";

    set_error_handler(
        function ($severity, $message, $file, $line) {
            throw new ErrorException($message, $severity, $severity, $file, $line);
        }
    );
    
    try {
        $screenshot_json_data = file_get_contents($url);
        $screenshot_result = json_decode($screenshot_json_data, true);
        // print_r($screenshot_result );exit;
        $screen_shot = $screenshot_result['lighthouseResult']['audits']['final-screenshot']['details']['data'];
        $screenshot_image = "<img src=".$screen_shot." class='img-responsive img-thumbnail'/>";
    }
    catch (Exception $e) {
        $screenshot_imag= $e->getMessage();
    }
    
    restore_error_handler();
    
       
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Captured External URL Screenshot</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<div>
<div class="row">
    <div class="col-sm-6">
    <h2>External URL Screenshot</h2>
    <form method="POST">
        <div class="form-group">
        <label for="email">URL:</label>
        <input type="text" class="form-control" placeholder="Eg:https://www.itinfotech.in" name="url">
        </div>
        <button type="submit" class="btn btn-default">Submit</button>
    </form>
    </div>
    <div class="col-sm-6">
    <?php echo $screenshot_image;?>
    </div>
  </div>
</div>

</body>
</html>

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *