使用 curl 和 PHP 保存文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1006604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving file using curl and PHP
提问by Haim Evgi
How can I save a file using curl and PHP?
如何使用 curl 和 PHP 保存文件?
回答by Haim Evgi
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
$file: 是要检索的对象的文件名
$local_path: is the local path to the directory to store the object
$local_path: 是存储对象的目录的本地路径
$newfilename: is the new file name on the local system
$newfilename: 是本地系统上的新文件名
回答by Jonathan Fingland
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.phpand http://us3.php.net/manual/en/function.fwrite.php
请参阅:http: //jp2.php.net/manual/en/function.curl-exec.php和http://us3.php.net/manual/en/function.fwrite.php
回答by rangalo
I think curl has -o option to write the output to a file instead of stdout.
我认为 curl 有 -o 选项可以将输出写入文件而不是标准输出。
After -o you have to provide the name of the output file.
在 -o 之后,您必须提供输出文件的名称。
example:
例子:
curl -o path_to_the_file url

