php 代码 压缩,PHP实现zip压缩的代码

/**

* Class xZip

*

* $xZip = new xZip;

* $xZip->zip(null, 'D:/www/log/index.php', 'D:/www/log/index.zip');

* $xZip->zipAll(array('D:/www/log/index.php','D:/www/log/lottery.sql'), 'D:/www/log/index_all.zip');

*

*/

class xZip

{

public function __construct()

{

}

/**

* add multi file to ZIP file

* @param array $source will be add to ZIP file list.

* @param null $destination ZIP file path

* @return null $destination

* @throws Exception

*/

public function zipAll($source = array(), $destination = null, $originPath = '')

{

if ($destination == null) {

throw new Exception('param $destination must be not null.');

}

if (count($source) == 0) {

throw new Exception('must be added one file.');

}

$zip = new ZipArchive;

@mkdir($this->getParentPath($destination), 0777, true);

$res = $zip->open($destination, ZipArchive::CREATE);

if ($res != true) {

throw new Exception('open zip(' . $destination . ') file error[' . $res . '].');

}

foreach ($source as $path) {

$zip->addFile($path, iconv('UTF-8', 'GB2312', str_replace($originPath, NULL, $path)));

}

$zip->close();

return $destination;

}

/**

* add one file to ZIP file.

* @param null $zip @ZipArchive object

* @param null $source will be add to ZIP file.

* @param null $destination dest ZIP file.

* @return null $destination

* @throws Exception

*/

public function zip($zip = null, $source = null, $destination = null)

{

if ($destination == null) {

throw new Exception('param $destination must be not null.');

}

if ($source == null) {

throw new Exception('must be added one file.');

}

if ($zip == null) {

$zip = new ZipArchive;

@mkdir($this->getParentPath($destination), 0777, true);

$res = $zip->open($destination, ZipArchive::CREATE);

if ($res != true) {

throw new Exception('open zip(' . $destination . ') file error[' . $res . '].');

}

}

//iconv('UTF-8','GB2312',str_replace($this->getParentPath($source).'/', NULL, $source)

$zip->addFile($source, str_replace($this->getParentPath($source) . '/', NULL, $source));

$zip->close();

return $destination;

}

/**

* @param $source zip file path

* @param $destination dest directory path

*/

public function unzip($source, $destination)

{

@mkdir($destination, 0777, true);

$zip = new ZipArchive;

if ($zip->open($source) === true) {

$zip->extractTo($destination);

$zip->close();

}

}

public function __destruct()

{

}

private function getParentPath($destination)

{

$path = substr($destination, 0, strripos($destination, '/'));

return $path;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值