php curl和下载文件[复制]

2ekbmq32  于 2023-02-03  发布在  PHP
关注(0)|答案(1)|浏览(160)
    • 此问题在此处已有答案**:

php - How to force download of a file?(7个答案)
2天前关闭。
截至2天前,社区正在审查是否重新讨论此问题。
我想使用invoiz api下载发票:www.example.comhttps://app.invoiz.de/api/documentation/#/invoices/download%20InvoiceDocument
我的代码:

// DOWNLOAD INVOICES
$curl = curl_init('https://app.invoiz.de/api/invoice/ID_OF_INVOICE/download');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_USERPWD, $apiKey . ":" . $secretApiKey); 
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer '.$token->token,
    'accept: application/pdf'
));

$content = curl_exec($curl);
curl_close($curl);

echo $内容显示:

但是我想下载pdf文件,我该如何实现呢?
CURL响应:

access-control-allow-origin: *  
connection: keep-alive  
content-disposition: attachment; filename="MyFileName.pdf"  content-type: application/pdf  
date: Tue,31 Jan 2023 10:50:24 GMT  
strict-transport-security: max-age=7776000; includeSubDomains; preload  
transfer-encoding: chunked
t9aqgxwy

t9aqgxwy1#

你必须把标题到pdf格式,这样你的浏览器才能理解它是pdf格式。

header('Content-Type: application/pdf');

或者强制下载类似的东西:

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file) . "\"");

相关问题