1、读取文件内容下载
$filePath = DATA_PATH . '/zip/' . 'test.zip'; //下载到本地的本地文件路径
$wfp = fopen($filePath,'a'); //累加写
$fp = fopen($url, 'rb'); //在线文件地址
if ($fp === false) exit('文件不存在或打开失败');
$chunkSize = 1024 * 1024; //每读取1M写入一次,避免内存溢出
while (!feof($fp)) {
$buffer = fread($fp, $chunkSize); //读取
fwrite($wfp, $buffer); //写入本地文件
// echo $buffer; //直接输出
// ob_flush();
// flush();
}
fclose($fp);
fclose($wfp); //写入完成,关闭句柄
2、curl直接获取文件内容下载,存在内存溢出
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata = curl_exec($ch);
curl_close($ch);
// 使用中文文件名时需要转码
$filePath = DATA_PATH . '/zip/' . 'test.zip';
$fp = fopen($filePath,'w');
fwrite($fp, $rawdata); //写入
fclose($fp);
3、直接读取写入本地文件,存在内存溢出
$opts = array(
'http' => array(
'method' => 'GET',
'timeout' => 300,
),
);
$context = stream_context_create($opts);
$fileContent = file_get_contents($url, false, $context);
// 使用中文文件名时需要转码
$filePath = DATA_PATH . '/zip/' . 'test.zip';
$fp = fopen($filePath,'w');
fwrite($fp, $fileContent); //写入
fclose($fp);