2012-07-08 128 views
2

我們有像一些HTML代碼:有文件和文件夾使用ZIP

<body>Some text</body> 

和可變$contents

我第一次在php中使用zip,有幾個問題。

我如何:

  1. 創建一個名爲HTML文件夾,並把它放在裏面$contents沒有真正建立對FTP,只是變量)

  2. 創建index.html並把它裏面HTML這是裏面的文件夾$contents

    所以$contents在zip之前sh烏爾德包含:

    /HTML/index.html (with <body>Some text</body> code inside) 
    
  3. 創建一個zip壓縮文件裏面$contents變量的所有內容。

回答

1

如果我理解正確:

$contents = '/tmp/HTML'; 
// Make the directory 
mkdir($contents); 
// Write the html 
file_put_contents("$contents/index.html", $html); 
// Zip it up 
$return_value = -1; 
$output = array(); 
exec("zip -r contents.zip $contents 2>&1", $output, $return_value); 
if ($return_value === 0){ 
    // No errors 
    // You now have contents.zip to play with 
} else { 
    echo "Errors!"; 
    print_r($output); 
} 

我不使用庫來壓縮它,只需在命令行,但如果你願意,你可以使用一個庫(但我檢查查看zip是否正確執行)。


如果你真的想這樣做真正在內存中的一切,你可以這樣做:

$zip = new ZipArchive; 
if ($zip->open('contents.zip') === TRUE) { 
    $zip->addFromString('contents/index.html', $html); 
    $zip->close(); 
    echo 'ok'; 
} else { 
    echo 'failed'; 
} 

http://www.php.net/manual/en/ziparchive.addfromstring.php

+0

mkdir創建文件夾和file_put_contents在ftp上創建文件,我不想做的事情。這個想法是在變量內創建文件夾和文件,並將結果壓縮。沒有真正的創造,所有的行爲都應該記憶。不管怎樣,謝謝。 – James 2012-07-08 10:16:28

+0

如果你在'/ tmp'中做了所有的事情,那麼技術上可以滿足你的要求,因爲'/ tmp'是一個安裝在RAM(即內存)中的文件系統。不過,請參閱我的編輯,以便在PHP內存中完成整個操作。 – Jay 2012-07-08 10:24:20

0

我會建議使用ZipArchive類。所以你可以有這樣的東西

$html = '<body>some HTML</body>'; 
$contents = new ZipArchive(); 
if($contents->open('html.zip', ZipArchive::CREATE)){ 
    $contents->addEmptyDir('HTML'); 
    $contents->addFromString('index.html', $html); 
    $contents->close() 
} 
相關問題