使用 cURL 将图像下载到 ZipArchive
我正在尝试通过 API 从社交网站将图像下载到 ZipArchive,我使用以下代码:
...
public function downloadAlbumZip($album_name, $photos)
{
$zip = new ZipArchive();
$album_name = $this->_cleanAlbumName($album_name);
$filename = 'album.zip';
$file = tempnam(PHOTOS, "{$album_name}-").'.zip';
if ($zip->open($file, ZIPARCHIVE::CREATE) === TRUE)
{
foreach ($photos as $photo) {
$image = $photo['pid'] . '.jpg';
$binary = $this->_getImage($photo['src']);
$zip->addFromString($image, $binary);
}
$output = print_r($zip, true);
$zip->close();
exit('Zip Saved.<br /><a href="javascript:history.go(-1);">Back to Album Overview</a>');
} else {
die('Zip Failed.');
}
}
private function _getImage($img)
{
if ( function_exists('curl_init') )
{
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawdata = curl_exec($ch);
curl_close($ch);
return $rawdata;
}
}
...
它可以工作,但速度非常慢,并且经常以超时错误结束,任何人都可以推荐一种加快速度的方法吗?向上?
谢谢
I'm trying to download images to a ZipArchive, from a social networking site via their API, I'm using the following code:
...
public function downloadAlbumZip($album_name, $photos)
{
$zip = new ZipArchive();
$album_name = $this->_cleanAlbumName($album_name);
$filename = 'album.zip';
$file = tempnam(PHOTOS, "{$album_name}-").'.zip';
if ($zip->open($file, ZIPARCHIVE::CREATE) === TRUE)
{
foreach ($photos as $photo) {
$image = $photo['pid'] . '.jpg';
$binary = $this->_getImage($photo['src']);
$zip->addFromString($image, $binary);
}
$output = print_r($zip, true);
$zip->close();
exit('Zip Saved.<br /><a href="javascript:history.go(-1);">Back to Album Overview</a>');
} else {
die('Zip Failed.');
}
}
private function _getImage($img)
{
if ( function_exists('curl_init') )
{
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawdata = curl_exec($ch);
curl_close($ch);
return $rawdata;
}
}
...
Which works but is very slow and often ends in a timeout error, can anyone recommend a way to speed this up?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该先下载所有图像,验证它们是否正常,然后在超时时重新下载。
您可以使用 CURL_MULTI_EXEC 并行执行图像下载,从而加快图像下载速度。
请记住,加速任何事情的关键是确定瓶颈在哪里。是压缩文件吗?如果是这种情况,您可以使用本机二进制文件并退出。是下载图片吗?是图片的大小吗?
您应该进行一些分析,即使它只是回显
time()
来查看哪些操作花费的时间最长。You should download all the images first, verify that they are okay, then re-download on timeout.
You can speed images downloading by doing them in parallel using CURL_MULTI_EXEC.
Remember, the key to speeding up anything is to identify where the bottleneck is. Is it zipping the files? You could use a native binary and shell out if that is the case. Is it downloading the images? Is it the size of the images?
You should do some profiling, even if it is just echoing
time()
to see which operations are taking the longest.