2015-07-09 47 views
0

我想知道爲什麼這個download()函數不起作用。PHP中的捲曲進度函數

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

我想創建一個JSON文件,但它並沒有創造。它在聲明下載之外的進度後立即生效。 –

回答

0

聲明你的函數progressdownload

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