Saving file using curl and PHP

2020-02-01 18:17发布

How can I save a file using curl and PHP?

标签: php xml curl
3条回答
别忘想泡老子
2楼-- · 2020-02-01 18:55

did you want something like this ?

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 

Functionality: Its a function and accepts three parameters

get_file($file, $local_path, $newfilename)

$file : is the filename of the object to be retrieved

$local_path : is the local path to the directory to store the object

$newfilename : is the new file name on the local system

查看更多
霸刀☆藐视天下
3楼-- · 2020-02-01 19:00

I think curl has -o option to write the output to a file instead of stdout.

After -o you have to provide the name of the output file.

example:


curl -o path_to_the_file url
查看更多
走好不送
4楼-- · 2020-02-01 19:15

You can use:

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

?>

See: http://jp2.php.net/manual/en/function.curl-exec.php and http://us3.php.net/manual/en/function.fwrite.php

查看更多
登录 后发表回答