PHP + PDF,如何使用curl保存下载的PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15897264/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:09:24  来源:igfitidea点击:

PHP + PDF, how to save a downloaded PDF using curl?

phppdfcurlheadersave

提问by Kuba

Welcome

欢迎

I have a little problem with saving the downloaded pdf on the page. To download pdf I use Curl:

我在页面上保存下载的 pdf 时遇到了一些问题。要下载 pdf,我使用 Curl:

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$Result = curl_exec($CurlConnect);

Now in $Result(string) i have all PDF file content. And now begins my problem. I would like to save the downloaded pdf:

现在在$Result(string) 我有所有的 PDF 文件内容。现在开始我的问题。我想保存下载的pdf:

header('Cache-Control: public'); 
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.filesize($Result));
readfile($Result);

Unfortunately, when I save or open a new PDF file, I get a blank document. Perhaps the problem is with the last lines of:

不幸的是,当我保存或打开一个新的 PDF 文件时,我得到一个空白文档。也许问题出在最后几行:

header('Content-Length: '.filesize($Result));
readfile($Result);

Unfortunately, I do not know what to change them to make it work ... I ask for your help. Thanks

不幸的是,我不知道如何更改它们以使其工作......我请求您的帮助。谢谢

回答by Khaleel

Both filesizeand readfileaccepts files as arguments. You are providing a string instead of a file.

无论文件大小ReadFile的接受文件作为参数。您提供的是字符串而不是文件。

Please try this.

请试试这个。

$CurlConnect = curl_init();
curl_setopt($CurlConnect, CURLOPT_URL, 'http://website.com/invoices/download/1');
curl_setopt($CurlConnect, CURLOPT_POST,   1);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_POSTFIELDS, $request);
curl_setopt($CurlConnect, CURLOPT_USERPWD, $login.':'.$password);
$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;

回答by mkjasinski

Maybe that:

也许是:

// ...
$Result = curl_exec($CurlConnect);
$file = 'file.pdf';
$fileName = 'fileName.pdf';
file_put_contents($file, $Result);

and than:

然后:

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

readfile($file);

I hope I helped!

我希望我有所帮助!