php - 使用 CURL 从 URL 下载文件

标签 php curl download

我尝试使用 php 脚本从如下 URL 下载文件:

http://www.xcontest.org/track.php?t=2avxjsv1.igc

我使用的代码如下所示,但它只生成空的下载文件:

$DLFile= "testfile.igc";
$DLURL="http://www.xcontest.org/track.php?t=2avxjsv1.igc"; 
$fp = fopen ($DLFile, 'w+');
$ch = curl_init($DLURL);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
curl_close($ch);
fclose($fp);

另一个奇怪的事情是在网络浏览器中输入 URL 时我没有得到文件。我只能在单击 web site 上的链接时才能下载文件!

非常感谢任何建议!

最佳答案

试一试

<?php

    $output_filename = "testfile.igc";

    $host = "http://www.xcontest.org/track.php?t=2avxjsv1.igc";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $host);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($ch, CURLOPT_REFERER, "http://www.xcontest.org");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec($ch);
    curl_close($ch);

    print_r($result); // prints the contents of the collected file before writing..


    // the following lines write the contents to a file in the same directory (provided permissions etc)
    $fp = fopen($output_filename, 'w');
    fwrite($fp, $result);
    fclose($fp);
?>
#

或者如果你想把它放在一个循环中来解析几个链接......你需要一些函数......这是一个粗略的想法......

<?php

    function collect_file($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, false);
        curl_setopt($ch, CURLOPT_REFERER, "http://www.xcontest.org");
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        return($result);
    }

    function write_to_file($text,$new_filename){
        $fp = fopen($new_filename, 'w');
        fwrite($fp, $text);
        fclose($fp);
    }


    // start loop here

    $new_file_name = "testfile.igc";
    $url = "http://www.xcontest.org/track.php?t=2avxjsv1.igc";

    $temp_file_contents = collect_file($url);
    write_to_file($temp_file_contents,$new_file_name)

    // end loop here
?>

关于php - 使用 CURL 从 URL 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13168198/

相关文章:

php - 存储文本区域的换行符和缩进

php - Laravel 新应用程序名称命令代客错误

php - 将表单字段保存在组件参数 joomla 中

php - Paypal 无法列出协议(protocol) ID 的协议(protocol)交易

python - 在python中从网上下载一个excel文件

python - 进度条在 Python 中无法正常工作

php - 存储过程中的 OUT 参数声明

curl - 无法使用 curl 发送 HTTP/2 请求

curl 跟随位置错误

c# - 分段的 C# 文件下载器