使用 PHP 从 url 添加文件创建 zip

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13930049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 06:17:39  来源:igfitidea点击:

Create zip with PHP adding files from url

phpdownloadzip

提问by ngplayground

I was wondering if the following is possible to do and with hope someone could potentially help me.

我想知道是否可以执行以下操作,并希望有人可以帮助我。

I would like to create a 'download zip' feature but when the individual clicks to download then the button fetches images from my external domain and then bundles them into a zip and then downloads it for them.

我想创建一个“下载 zip”功能,但是当个人点击下载时,该按钮会从我的外部域中获取图像,然后将它们捆绑到一个 zip 文件中,然后为他们下载。

I have checked on how to do this and I can't find any good ways of grabbing the images and forcing them into a zip to download.

我已经检查了如何执行此操作,但找不到任何抓取图像并将它们强制压缩为 zip 下载的好方法。

I was hoping someone could assist

我希望有人可以提供帮助

回答by Prisoner

# define file array
$files = array(
    'http://google.com/images/logo.png',
    'http://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Wikipedia-logo-en-big.png/220px-Wikipedia-logo-en-big.png',
);

# create new zip object
$zip = new ZipArchive();

# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);

# loop through each file
foreach ($files as $file) {
    # download file
    $download_file = file_get_contents($file);

    #add it to the zip
    $zip->addFromString(basename($file), $download_file);
}

# close zip
$zip->close();

# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);

Note: This solution assumes you have allow_url_fopenenabled. Otherwise look into using cURL to download the file.

注意:此解决方案假定您已allow_url_fopen启用。否则考虑使用 cURL 下载文件。

回答by Deus Deceit

I hope I didn't understand wrong.

我希望我没有理解错。

http://php.net/manual/en/book.zip.php

http://php.net/manual/en/book.zip.php

I haven't tried this, but it seems like what you're looking for.

我没有试过这个,但它似乎是你正在寻找的。

<?php
$zip = new ZipArchive;

if ($zip->open('my_archive.zip') === TRUE) {
    $zip->addFile($url, basename($url));
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>