My Class 直接从链接下载文件:
MyClass{
function download($link){
......
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_FILE, $File->handle);
curl_setopt($ch,CURLOPT_WRITEFUNCTION , array($this,'__writeFunction'));
curl_exec($ch);
curl_close($ch);
$File->close();
......
}
function __writeFunction($curl, $data) {
return strlen($data);
}
}
我想知道下载文件时如何使用 CRULOPT_WRITEFUNCTION。 上面的代码如果我删除行:
curl_setopt($ch,CURLOPT_WRITEFUNCTION , array($this,'__writeFunction'));
然后它会运行良好,我可以下载该文件。但如果我使用 CURL_WRITEFUNCTION 选项,我无法下载文件。
最佳答案
我知道这是一个老问题,但也许我的回答会对您或其他人有所帮助。试试这个:
function get_write_function(){
return function($curl, $data){
return strlen($data);
}
}
我不知道你到底想做什么,但是使用 PHP 5.3,你可以用回调做很多事情。以这种方式生成函数的真正好处在于,通过 'use' 关键字传递的值随后会保留在函数中,有点像常量。
function get_write_function($var){
$obj = $this;//access variables or functions within your class with the object variable
return function($curl, $data) use ($var, $obj) {
$len = strlen($data);
//just an example - you can come up with something better than this:
if ($len > $var){
return -1;//abort the download
} else {
$obj->do_something();//call a class function
return $len;
}
}
}
您可以将函数作为变量检索,如下所示:
function download($link){
......
$var = 5000;
$write_function = $this->get_write_function($var);
$ch = curl_init($link);
curl_setopt($ch, CURLOPT_FILE, $File->handle);
curl_setopt($ch, CURLOPT_WRITEFUNCTION , $write_function);
curl_exec($ch);
curl_close($ch);
$File->close();
......
}
这只是一个例子。你可以在这里看到我是如何使用它的:Parallel cURL Request with WRITEFUNCTION Callback .我实际上并没有测试所有这些代码,所以可能会有一些小错误。如果您有问题,请告诉我,我会解决它。
关于php - 通过 CURL 下载文件时如何使用 CURLOPT_WRITEFUNCTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5359787/