【问题标题】:Saving file using curl and PHP使用 curl 和 PHP 保存文件
【发布时间】:2010-11-03 15:28:08
【问题描述】:

如何使用 curl 和 PHP 保存文件?

【问题讨论】:

  • 您确定需要 curl 吗? file_get_contents("whatever.com") 还不够吗?
  • 我确信 14,000 次浏览中超过 50% 的人认为file_get_contents 不够

标签: php xml curl


【解决方案1】:

你想要这样的东西吗?

function get_file($file, $local_path, $newfilename) 
{ 
    $err_msg = ''; 
    echo "<br>Attempting message download for $file<br>"; 
    $out = fopen($local_path.$newfilename,"wb");
    if ($out == FALSE){ 
      print "File not opened<br>"; 
      exit; 
    } 

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_FILE, $out); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_URL, $file); 

    curl_exec($ch); 
    echo "<br>Error is : ".curl_error ( $ch); 

    curl_close($ch); 
    //fclose($handle); 

}//end function 

功能: 它是一个函数,接受三个参数

get_file($file, $local_path, $newfilename)

$file:是要检索的对象的文件名

$local_path:是存放对象的目录的本地路径

$newfilename:是本地系统上的新文件名

【讨论】:

    【解决方案2】:

    你可以使用:

    <?php
    // create a new cURL resource
    $ch = curl_init();
    
    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_HEADER, 0);
    
    // grab URL and pass it to the browser
    $out = curl_exec($ch);
    
    // close cURL resource, and free up system resources
    curl_close($ch);
    
    
    $fp = fopen('data.txt', 'w');
    fwrite($fp, $out);
    fclose($fp);
    
    ?>
    

    见:http://jp2.php.net/manual/en/function.curl-exec.phphttp://us3.php.net/manual/en/function.fwrite.php

    【讨论】:

    • 这将对小文件完成这项工作,但它会在保存之前将整个文件加载到内存中,因此如果文件大于 PHP 的内存限制,您可能会遇到致命的“内存不足”错误. Haim Evgi 的回答正确地将文件流式传输到磁盘,从而避免了这个问题。
    • curl_exec 直接进入 file_put_contents()。至少,它节省了 3 行代码。
    【解决方案3】:

    我认为 curl 有 -o 选项可以将输出写入文件而不是标准输出。

    在 -o 之后,您必须提供输出文件的名称。

    示例:

    curl -o path_to_the_file 网址

    【讨论】:

    • 这适用于 命令行 版本的 curl,但不适用于 PHP curl 库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多