使用 CURL 从 URL 下载文件 [英] Download file from URL using CURL

查看:51
本文介绍了使用 CURL 从 URL 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to download file using a php-script from an URL like the following:

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

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

The code I use looks like the following, but it produces empty download files only:

$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 时我没有得到文件.我只能在点击 网站

An other strange thing is when entering the URL in the web browser I don't get the file. It can I could only download the file when clicking the link on the 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);
?>

#

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

#

or if you want to put it within a loop for parsing several links... you need some functions.. here is a rough idea....

<?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
?>

这篇关于使用 CURL 从 URL 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆