2012-12-18 47 views
13

添加的文件,我在想,如果下面是可以做到的,并希望有人可能帮助我拉链。创建PHP从URL

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

我已经检查了如何做到这一点,我无法找到抓取的图像,并迫使他们到一个zip下载的任何好办法。

我希望有人能帮助

+4

您正在描述相当复杂的一组操作 - 您问题不具体。这有什么部分是你有问题?你有什么尝试? – symcbean

+1

我更加好奇,如果有这样的方式来从外部域下载图像到一个zip文件。我目前researchign可能性 – ngplayground

回答

38
# 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); 

注意:此方法假定您已经启用allow_url_fopen。否则,请使用cURL来下载文件。

+0

我收到下面的“Windows无法打开该文件夹压缩(zipped文件夹‘C:\ download.zip’无效 – ngplayground

+0

@DonaldSutherland看到我的编辑我与变量名的一些愚蠢的东西 – Prisoner

+2

。非常感谢的作品就像一个魅力! – ngplayground

2

我希望我没有理解错了。

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

我没有试过,但它好像你在找什么。

<?php 
$zip = new ZipArchive; 

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