2013-04-09 117 views
5

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

我在保存页面上下载的pdf时遇到了一些问题。下载PDF我使用卷曲:

$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); 

现在$结果(串),我有所有的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); 

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

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

不幸的是,我不知道是什么改变它们,使其工作......我请求你们的帮助。由于

+0

你为什么不使用http://php.net/manual/en/function.pdf-save.php – 2013-04-09 08:57:41

+0

我认为这是在你的代码中的一些错误发生的历史。将代码包装在try-catch块中并添加一些调试步骤。 – Khaleel 2013-04-09 09:00:35

+1

我没有测试,但我认为对于'filesize()'和'readfile()',你需要一个真实文件的路径,而不是字符串的内容。 – enenen 2013-04-09 09:03:52

回答

10

filesizereadfile都接受文件作为参数。您提供的是字符串而不是文件。

请试试这个。

$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; 
+0

是的你有权:) – Kuba 2013-04-09 09:14:10

0

也许是:

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

比:

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); 

我希望我帮助!