note 33669 deleted from ref.java by aidan
| From: | aidan@php.net | Date: | Wed, 01 Sep 2004 00:08:35 +0000 |
| Subject: | note 33669 deleted from ref.java by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-75801@lists.php.net to get a copy of this message | ||
Note Submitter: chris at mad-teaparty dot com
----
This snippet shows how to write ZIP-Files using PHP's Java-API:
---------------------------
// specify the name of the zip file to be created
$zipfile = "/usr/local/apache/htdocs/skripte/test.zip";
// files that should be zipped
$filenames = array("test.php", "index.html");
// create a zip output stream
$out = new Java('java.util.zip.ZipOutputStream', new
Java('java.io.FileOutputStream', $zipfile));
// walk through the array an add each file to the archive
foreach ($filenames as $entry) {
$content = implode("", file($entry)); // read the file
$zipentry = new Java('java.util.zip.ZipEntry', $entry); //define a new zip entry
$out->putNextEntry($zipentry); //write this entry to the archive
$out->write($content, 0, strlen($content)); //add the content
$out->closeEntry(); // close the current entry
}
$out->setComment("test..."); // set a comment for the zip file
$out->close(); //close the output stream
----------------------------
This is just "proof of concept". It doesn't set all values for zip entries, like
CRC32-checksum, compressed size etc.
Several hints:
- in order to read or write JAR-archives, the snippet needs only few modification: replace the
ZIPOutputStream with an instance of "JarOutputStream" or "JarInputStream",
defined in "java.util.jar"
- use double backslashes for path names on Windows, eg. "C:\\apache\\htdocs\\index.html"
- if you specify an absolute path name for a single zip entry, a directory will be created in the
zip archive. Thus, you can "zip" whole directories by walking through them
- If you want to set the time when the zip entry was added, note that the Java-method
"setTime" requires a long value (millisec). I did this:
$zipentry->setTime(time()*1000);
- If you want to add the CRC-checksum to each zip entry, do not (!) use PHP's crc32-function!
Incompatible types will cause loss of precision and wrong checksums. Use the Java-class
"CRC32" instead:
$crc32 = new Java('java.util.zip.CRC32');
$crc32->update($content);
$zipentry->setCrc($crc32->getValue());
$crc32->reset();