我想知道为什么这个download()函数无效。
function download($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);
function progress($resource, $download_size, $downloaded, $upload_size, $uploaded)
{
if ($download_size > 0)
$progress = round($downloaded / $download_size * 100);
$progress = array('progress' => $progress);
$path = "temp/";
$destination = $path."11.json";
$file = fopen($destination, "w+");
fwrite($file, json_encode($progress, JSON_UNESCAPED_UNICODE));
fclose($file);
}
}
download("http://stackoverflow.com");
但是当我使用没有像
这样的功能时curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com");
或当我使用该功能两次时
download("http://stackoverflow.com");
download("http://stackoverflow.com");
它有效。否则它不会创建任何json文件。
答案 0 :(得分:0)
在progress
之外声明您的函数download
:
function download($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
$html = curl_exec($ch);
curl_close($ch);
}
function progress($resource, $download_size, $downloaded, $upload_size, $uploaded)
{
if ($download_size > 0)
$progress = round($downloaded / $download_size * 100);
$progress = array('progress' => $progress);
$path = "temp/";
$destination = $path."11.json";
$file = fopen($destination, "w+");
fwrite($file, json_encode($progress, JSON_UNESCAPED_UNICODE));
fclose($file);
}