How to Screenshot a Webpage in PHP
When screenshotting webpages, consistency is key. Using a few lines of PHP code, we can consistently render and screenshot important webpages with ease.
In the brief demonstration below, we’ll learn how to call a free webpage screenshot API using ready-to-run PHP code examples.
We can start by installing the client SDK. Let’s execute the below command from the command line to install using composer:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, let’s grab a free Cloudmersive API key to authorize our requests. This will allow us to make up to 800 free API calls per month with no additional commitments.
To wrap up, let’s copy the remaining PHP code examples into our file:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ConvertWebApi(
new GuzzleHttp\Client(),
$config
);
$input = new \Swagger\Client\Model\ScreenshotRequest(); // \Swagger\Client\Model\ScreenshotRequest | Screenshot request parameters
try {
$result = $apiInstance->convertWebUrlToScreenshot($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ConvertWebApi->convertWebUrlToScreenshot: ', $e->getMessage(), PHP_EOL;
}
?>
We can structure our input like the JSON example shown below. In our request, we can specify extra loading wait time (to help fully render slower websites), and we can even customize the height and width of our screenshot:
{
"Url": "string",
"ExtraLoadingWait": 0,
"ScreenshotWidth": 0,
"ScreenshotHeight": 0
}
All done — no more code required! Now we can easily screenshot webpages using a URL and just a few lines of PHP code.