使用php代码下载远程PDF

时间:2017-08-02 10:19:35

标签: php pdf curl

我想将pdf文件从服务器下载到我的本地设备。 我使用了以下代码:

$url="https://www.example.com/test.pdf";
    $file = fopen(dirname(__FILE__) ."/PDF Files/".$filename, 'w+');
    $curl = curl_init($url);
    curl_setopt_array($curl, [
                                CURLOPT_URL            => $url,
                                CURLOPT_BINARYTRANSFER => 1, // No effect from PHP 5.1.3
                                CURLOPT_RETURNTRANSFER => 1,
                                CURLOPT_FILE           => $file,
                                CURLOPT_TIMEOUT        => 50,
                                CURLOPT_USERAGENT      => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)'
                                ]);
    $response = curl_exec($curl);

运行代码后,我在本地设备上找到PDF文件但是当我打开它时,我收到一条消息,说明文件已损坏。 有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我用过类似任务的代码是:

$url  = '"https://www.example.com/test.pdf';
$savePath= 'test.pdf';


$ch = curl_init($url);
if($ch === false)
{
    die('Failed to create curl handle');
}

$fp = fopen($savePath, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

您也可以尝试使用“禁用”标题:

 curl_setopt($soap_do, CURLOPT_HTTPHEADER, 0);

编辑2:

可能对您有所帮助的另外几个SA问题:

Download remote PDF using php code

why my downloaded file is alwayes damaged or corrupted?