如何通过PHP CURL调用Invoiz API实现PDF发票下载?
使用Invoiz API下载PDF发票的问题解决方法
问题描述
我希望通过Invoiz API下载发票,当前使用的PHP CURL代码如下:
// 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 $content显示乱码,但我需要实现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
解决方案
乱码是因为直接输出了PDF的二进制原始内容,浏览器无法识别为可下载文件。要实现浏览器触发PDF下载,需在输出内容前发送正确的HTTP响应头,告知浏览器文件类型和下载行为。
修改后的代码如下:
// 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); // 从响应头提取官方返回的文件名 $filename = "default_invoice.pdf"; // 自定义默认文件名 $responseHeaders = curl_getinfo($curl, CURLINFO_HEADER_OUT); if (preg_match('/filename="(.*)"/', $responseHeaders, $matches) && !empty($matches[1])) { $filename = $matches[1]; } curl_close($curl); // 发送HTTP响应头,触发浏览器下载 header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Content-Length: ' . strlen($content)); // 输出PDF二进制内容 echo $content; exit;
核心要点
- 必须先发送
Content-Type和Content-Disposition响应头,让浏览器识别这是需要下载的PDF文件,而非普通文本。 - 可从API返回的响应头中提取预设文件名,也可自行指定默认文件名。
- 添加
Content-Length头能让浏览器显示准确的下载进度,优化用户体验。
内容的提问来源于stack exchange,提问作者Trombone0904
相关产品推荐
相关产品推荐

