1
我正在嘗試使用cURL從具有多個連接的URL下載圖像以加速此過程。使用cURL多線程圖像下載,PHP
這裏是我的代碼:
function multiRequest($data, $options = array()) {
// array of curl handles
$curly = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
// loop through $data and create curl handles
// then add them to the multi-handle
foreach ($data as $id => $d) {
$path = 'image_'.$id.'.png';
if(file_exists($path)) { unlink($path); }
$fp = fopen($path, 'x');
$url = $d;
$curly[$id] = curl_init($url);
curl_setopt($curly[$id], CURLOPT_HEADER, 0);
curl_setopt($curly[$id], CURLOPT_FILE, $fp);
fclose($fp);
curl_multi_add_handle($mh, $curly[$id]);
}
// execute the handles
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
// get content and remove handles
foreach($curly as $id => $c) {
curl_multi_remove_handle($mh, $c);
}
// all done
curl_multi_close($mh);
}
和執行:
$data = array(
'http://example.com/img1.png',
'http://example.com/img2.png',
'http://example.com/img3.png'
);
$r = multiRequest($data);
因此,它不是真正的工作。它創建了3個文件,但與零個字節(空),並給我下面的錯誤(3次)和它的打印某種原始.PNGs的內容:
Warning: curl_multi_exec(): CURLOPT_FILE resource has gone away, resetting to default in /Applications/MAMP/htdocs/test.php on line 34
所以,請你能不能讓我知道如何解決它?
在此先感謝您的幫助!
以及在哪裏打開文件&寫&關閉? – Skylineman 2013-03-10 21:48:26
它作爲setopt調用的一部分打開。通常,資源在腳本結束時關閉,但如果需要關閉資源,則可以將資源分配給數組並在curl完成後關閉它們。 – datasage 2013-03-10 21:51:21
幫助謝謝:)我可以做'curl_multi_remove_handle'旁邊的'fclose'!再次感謝! – Skylineman 2013-03-10 23:06:02