PHP批量下载远程文件并zip压缩打包下载

PHP批量下载远程文件并zip压缩打包下载:


//示例数据
$files = array(
    'http://example.com/file1.jpg',
    'http://example.com/file2.jpg',
    'http://example.com/file3.jpg'
);
//下载压缩包的文件名
$zipFile = 'download.zip';

$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE) === true) {
    $multiHandle = curl_multi_init();
    $curlHandles = array();

    foreach ($files as $index => $fileUrl) {
        $curlHandles[$index] = curl_init($fileUrl);
        curl_setopt($curlHandles[$index], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curlHandles[$index], CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($curlHandles[$index], CURLOPT_CONNECTTIMEOUT, 10);
        curl_multi_add_handle($multiHandle, $curlHandles[$index]);
    }

    $running = null;
    do {
        curl_multi_exec($multiHandle, $running);
        curl_multi_select($multiHandle);
    } while ($running > 0);

    foreach ($curlHandles as $index => $handle) {
        $content = curl_multi_getcontent($handle);
        if (!empty($content)) {
            $zip->addFromString(basename($files[$index]), $content);
        }
        curl_multi_remove_handle($multiHandle, $handle);
    }

    curl_multi_close($multiHandle);

    $zip->close();

    // 提供下载链接给用户
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $zipFile . '"');
    header('Content-Length: ' . filesize($zipFile));
    readfile($zipFile);

    // 删除临时文件
    unlink($zipFile);
} else {
    echo 'Failed to create zip archive.';
}
?>

你可能感兴趣的:(php,php,开发语言)