Curl API调用Downloaded File

时间:2017-01-02 10:01:53

标签: php excel curl download

我正在使用curl从api调用中获取下载的Excel文件,在我的一个api调用中它返回一个excel文件,

我想强行下载那个Excel文件,我怎么能用curl做这个?

我尝试这样: -

$url = 'http://xyzwebsite.com/GetExcelParameterScheet';
$fields = array('TemplateID' => $id);
$method = 'POST';

// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
    die('Curl failed: ' . curl_error($ch));
}

// Close connection
curl_close($ch);

1 个答案:

答案 0 :(得分:1)

如果要将文件保存在服务器上,请添加

file_put_contents("sheet.xls",$result);

如果您想强制下载到网站访问者,请使用

header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"sheet.xls\""); 
echo $result;