0

我正在使用以下代码使用 php 从某个远程服务器下载文件

//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)。

我想这可能是标题内容的问题,但不知道确切......

谢谢

4

3 回答 3

1

http://php.net/manual/en/function.curl-setopt.php所述:

CURLOPT_RETURNTRANSFER: TRUE将传输作为 curl_exec() 的返回值的字符串返回,而不是直接输出。

所以你可以简单地在你的 curl_exec 行之前添加这一行:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

您将拥有 $data 变量中的内容。

于 2013-02-28T08:00:55.007 回答
1

我相信你需要:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

使 curl_exec() 返回数据,并且:

$data = curl_exec($ch);
fwrite($fp, $data);

获取实际写入的文件。

于 2013-02-28T07:18:26.743 回答
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;
    }
}
于 2013-07-09T01:33:52.907 回答