2013-04-04 134 views
1

我需要解析一系列php文件,以在使用zipArchive壓縮它們之前輸出.PDF和.PNG文件。我想要做的是類似由PHP文件生成的Zip文件

$zip = new ZipArchive(); 
$zip->open($file, ZipArchive::OVERWRITE); 

//If you access qr_gen.php on a browser it creates a QR PNG file. 
$zip->addFile('qr_gen.php?criteria=1', 'alpha.png'); 
$zip->addFile('qr_gen.php?criteria=2', 'beta.png'); 
//If you access pdf_gen.php on a browser it creates a PDF file. 
$zip->addFile('pdf_gen.php?criteria=A', 'instructions.pdf'); 

$zip->close(); 
header('Content-Type: application/zip'); 
header('Content-Length: ' . filesize($file)); 
header('Content-Disposition: attachment; filename="file.zip"'); 
readfile($file); 
unlink($file); 

這顯然不起作用。我怎樣才能實現我的目標?

$zip->addFile('qr_gen.php?criteria=1', 'alpha.png'); 

相反,你必須先下載PNG圖像,並將它們存儲在本地:當您提供和URL作爲文件名

回答

5

下面一行將無法正常工作。然後將它們添加到zip存檔。就像這樣:

file_put_contents('alpha.png', 
    file_get_contents('http://yourserver.com/qr_gen.php?criteria=1'); 

$zip->addFile('alpha.png'); 

你會發現在ZipArchive::addFile()

+1

此外,其他的東西給了我整個上午。由於我使用了for()循環,並且在for循環結束時取消了鏈接() - 臨時圖片,所以沒有寫入我的zip文件。我必須在循環開始時使用'$ zip-> open($ file)'並在'unlink($ temp_pic_file)之前使用'$ zip-> close()'' – Andrew 2013-04-04 15:14:33

+1

這很完美。但是,由於apache需要WRITE權限,我使用了具有770權限的'cache'子目錄'file_put_contents(「cache/alpha.png」,file_get_contents(「http://mydomain.com/qr_gen.php?ccriteria=1」)) ; $ zip-> addFile(「cache/alpha.png」,「alpha.png」);'另外,我將緩存目錄中創建的文件取消鏈接()。謝謝! – Andrew 2013-04-04 16:43:05

+0

好點。我應該提到這一點。 – hek2mgl 2013-04-04 16:53:18

0

首先的文檔頁面的詳細信息,執行所有文件複製到瀏覽器,並將該內容(png.pdf)到一個文件夾,然後創建通過一個一個地讀取它的zip。

希望它有幫助

1

你需要做的是先在本地獲取文件。如果您設置了URL fopen映射器,或者失敗,cURL調用,則可以(使用file_get_contents)來實現此功能。

這是一個樣的方式來做到這一點:

$zip = new ZipArchive(); 
$zip->open("zipfile.zip",ZipArchive::OVERWRITE); 
$URLs = array(
    "alpha.png" => "http://my.url/qr_gen.php?criteria=1", 
    "beta.png" => "http://my.url/qr_gen.php?criteria=2", 
    "instructions.pdf" => "http://my.url/pdf_gen.php?criteria=A"); 
foreach ($URLs as $file => $URL) { 
    $f = @file_get_contents($URL); 
    if (empty($f)) throw new Exception("File not found: ".$URL); 
    $zip->addFromString($file, $f); 
} 

你的zip文件,然後可作爲進一步處理ZIP $。