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.
Copy <?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);
?>
Copy <?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);
?>