【发布时间】:2010-11-03 15:28:08
【问题描述】:
如何使用 curl 和 PHP 保存文件?
【问题讨论】:
-
您确定需要 curl 吗? file_get_contents("whatever.com") 还不够吗?
-
我确信 14,000 次浏览中超过 50% 的人认为
file_get_contents不够
如何使用 curl 和 PHP 保存文件?
【问题讨论】:
file_get_contents 不够
你想要这样的东西吗?
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:是本地系统上的新文件名
【讨论】:
你可以使用:
<?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.php 和http://us3.php.net/manual/en/function.fwrite.php
【讨论】:
curl_exec 直接进入 file_put_contents()。至少,它节省了 3 行代码。
我认为 curl 有 -o 选项可以将输出写入文件而不是标准输出。
在 -o 之后,您必须提供输出文件的名称。
示例:
curl -o path_to_the_file 网址【讨论】: