php 从 Base64 字符串下载 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34698016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download PDF from Base64 string
提问by Marijn Roukens.com
My situation (all in PHP):
我的情况(全部在 PHP 中):
What I get: A Base64 encoded string from an API.
我得到的是:来自 API 的 Base64 编码字符串。
What I want: A link to click on that downloads this document as an PDF. (I am sure it will always be a PDF file)
我想要的是:点击链接可将本文档下载为 PDF。(我确定它永远是一个 PDF 文件)
I have tried this:
我试过这个:
$decoded = base64_decode($base64);
file_put_contents('invoice.pdf', $decoded);
but I am kind off lost, can't seem to find a way to download it after decoding it.
但我有点迷路了,解码后似乎找不到下载它的方法。
I hope someone can help me, thanks in advance!
我希望有人可以帮助我,在此先感谢!
回答by J. Titus
The example here seems helpful: http://php.net/manual/en/function.readfile.php
这里的例子似乎很有帮助:http: //php.net/manual/en/function.readfile.php
In your case:
在你的情况下:
<?php
$decoded = base64_decode($base64);
$file = 'invoice.pdf';
file_put_contents($file, $decoded);
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>
This should force the download to occur.
这应该会强制进行下载。
回答by Tomas Kuzminskas
Don't need to decode base64. You can send header with binary file.
不需要解码base64。您可以使用二进制文件发送标头。
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($filedata));
ob_clean();
flush();
echo $filedata;
exit;