Decode Base64 Async Responses in PHP
Learn to decode Base64-encoded binary responses from ScraperAPI Async in PHP. Process PDFs, images, and files with PHP and command-line examples.
The responses returned by the Async API for binary requests require you to decode the data as they are encoded using Base64
encoding. This allows the binary data to be sent as a text string, which can then be decoded back into its original form when you want to use it.
Example request:
<?php
$payload = json_encode(array(
"apiKey" => "API_KEY",
"url" => "https://pdfobject.com/pdf/sample.pdf"
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://async.scraperapi.com/jobs");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
} else {
echo $response;
}
curl_close($ch);
?>
Decode response:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://async.scraperapi.com/jobs/<JOB_ID>");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
exit;
}
$data = json_decode($response, true);
if (isset($data['response']['base64EncodedBody'])) {
$base64EncodedBody = $data['response']['base64EncodedBody'];
$pdfData = base64_decode($base64EncodedBody);
file_put_contents('name.pdf', $pdfData);
echo "PDF saved as name.pdf\n";
} else {
echo "Error: base64EncodedBody not found in the response.\n";
}
curl_close($ch);
?>
Last updated
Was this helpful?