使用API网址进行PHP curl请求下载PDF


Making PHP curl request to Download PDF using API url

如果直接在浏览器上运行,以下url将下载任何给定url的PDF。http://htmltopdfapi.com/querybuilder/api.php?url=http%3A%2F%2Fwww.google.com%2F

我需要在服务器中使用curl下载该文件。

我正在使用CURL请求来完成此操作。

$CurlConnect = curl_init();
$link = urlencode("https://www.google.com");
$source = "http://htmltopdfapi.com/querybuilder/api.php?url=$link";
curl_setopt($CurlConnect, CURLOPT_URL, $source);
curl_setopt($CurlConnect, CURLOPT_HEADER, true);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_NOBODY, true);
curl_setopt($CurlConnect, CURLOPT_TIMEOUT, 10);
curl_setopt($CurlConnect, CURLOPT_SSLVERSION,3);
$Result = curl_exec($CurlConnect);
header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.strlen($Result));
echo $Result;

上面的代码下载了pdf,但pdf已损坏,如何使其工作?

<?php
$ch = curl_init();
$link = urlencode("https://www.google.com");
$source = "http://htmltopdfapi.com/querybuilder/api.php?url=$link";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$destination = dirname(__FILE__) . '/file.pdf';
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
$filename = 'google.pdf';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($destination);

您的PDF已损坏,因为它还包含您从API获得的HTTP头。你似乎不需要标题,所以你可以删除这行:

curl_setopt($CurlConnect, CURLOPT_HEADER, true);

这里还要注意,添加Content-Disposition: attachment将使浏览器下载文件,而不是尝试渲染它

您还应该关闭您的cURL会话。有关更多详细信息,请参阅文档。