我正在尝试使用以下代码从一组URL中复制图像。问题是它只保存最后一张图片,任何人都知道为什么会这样?
foreach($photos['data'] as $photo)
{
echo "guardando:";
echo $photo['id'];
$idFoto++;
$fp = fopen('foto'.$idFoto.'.jpg', 'wb');
curl_setopt($ch, CURLOPT_URL, $photo['source']);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}
答案 0 :(得分:1)
我认为您的问题出在curl_close($ch)
,此调用应该在bucle之外,或者您可以为每张照片调用curl_init
,也可以检查curl_setopt
是返回true还是false:
foreach($photos['data'] as $photo)
{
echo "Guardando $idFoto: $photo['source']\n";
$idFoto++;
$fp = fopen('foto'.$idFoto.'.jpg', 'wb');
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $photo['source']);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
if(curl_exec($ch)===false) echo "Error: ".curl_error()."\n";
fclose($fp);
curl_close($ch);
}
另请注意,CURLOPT_RETURNTRANSFER
不需要,因为我们保存到文件而不是分配curl_exec
返回。你能测试吗?