我正在使用以下代码从某个远程服务器下载文件
//some php page parsing code
$url = 'http://www.domain.com/'.$fn;
$path = 'myfolder/'.$fn;
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
// some more code
但不是直接在目录中下载和保存文件,而是直接在浏览器上显示文件内容(垃圾字符为文件为zip)。
我想这可能是标题内容的问题,但不完全清楚......
谢谢
答案 0 :(得分:1)
我相信你需要:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
使curl_exec()返回数据,并且:
$data = curl_exec($ch);
fwrite($fp, $data);
获取实际写入的文件。
答案 1 :(得分:1)
如http://php.net/manual/en/function.curl-setopt.php中所述:
CURLOPT_RETURNTRANSFER:TRUE 将传输作为curl_exec()返回值的字符串返回,而不是直接输出。
所以你可以在curl_exec行之前添加这一行:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
您将获得$ data变量中的内容。
答案 2 :(得分:1)
使用以下包含错误处理的功能。
// Download and save a file with curl
function curl_dl_file($url, $dest, $opts = array())
{
// Open the local file to save. Suppress warning
// upon failure.
$fp = @fopen($dest, 'w+');
if (!$fp)
{
$err_arr = error_get_last();
$error = $err_arr['message'];
return $error;
}
// Set up curl for the download
$ch = curl_init($url);
if (!$ch)
{
$error = curl_error($ch);
fclose($fp);
return $error;
}
$opts[CURLOPT_FILE] = $fp;
// Set up curl options
$failed = !curl_setopt_array($ch, $opts);
if ($failed)
{
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
return $error;
}
// Download the file
$failed = !curl_exec($ch);
if ($failed)
{
$error = curl_error($ch);
curl_close($ch);
fclose($fp);
return $error;
}
// Close the curl handle.
curl_close($ch);
// Flush buffered data to the file
$failed = !fflush($fp);
if ($failed)
{
$err_arr = error_get_last();
$error = $err_arr['message'];
fclose($fp);
return $error;
}
// The file has been written successfully at this point.
// Close the file pointer
$failed = !fclose($fp);
if (!$fp)
{
$err_arr = error_get_last();
$error = $err_arr['message'];
return $error;
}
}