我正在尝试使用php中的ziparchive库压缩目录。 我是linux用户。目前我的目录结构是/ home / shivanshu / workspace / master-data / data /....
数据还包含文件和子目录,我想按原样压缩数据文件夹。我的代码在Linux中工作正常但是当我在windows中运行时,zip是从根文件夹创建的,即c /../../,这是不希望的
我的代码
public function createBatchZip($source, $destination, $tpodId){
$count = 0;
$response = [
'tpodResponse' => false,
'message' => ''
];
if (! extension_loaded ( 'zip' ) || ! file_exists ( $source )) {
$response = [
'tpodResponse' => false,
'message' => Messages::SOURCE_FOLDER_ERROR
];
return $response;
}
$zip = new \ZipArchive ();
if (! $zip->open ( $destination, \ZIPARCHIVE::CREATE )) {
$response = [
'tpodResponse' => false,
'message' => Messages::ZIP_CREATED_ERROR
];
return $response;
}
$source = str_replace ( '\\', '/', realpath ( $source ) );
if (is_dir ( $source ) === true) {
// Will exclude everything under these directories
$exclude = array('application', 'framework','tests','tools');
/**
* @param SplFileInfo $file
* @param mixed $key
* @param RecursiveCallbackFilterIterator $iterator
* @return bool True if you need to recurse or if the item is acceptable
*/
$filter = function ($file, $key, $iterator) use ($exclude) {
if ($iterator->hasChildren() && !in_array($file->getFilename(), $exclude)) {
return true;
}
return $file->isFile();
};
$innerIterator = new \RecursiveDirectoryIterator(
$source,
\RecursiveDirectoryIterator::SKIP_DOTS
);
$iterator = new \RecursiveIteratorIterator(
new \RecursiveCallbackFilterIterator($innerIterator, $filter)
);
//$files = new \RecursiveIteratorIterator ( new \RecursiveDirectoryIterator ( $source ), \RecursiveIteratorIterator::SELF_FIRST );
foreach ( $iterator as $file ) {
$file = str_replace ( '\\', '/', $file );
$file = realpath ( $file );
if (is_dir ( $file ) === true) {
$zip->addEmptyDir ( str_replace ( $source . '/', '', $file . '/' ) );
} else if (is_file ( $file ) === true) {
$zip->addFromString ( str_replace ( $source . '/', '', $file ), file_get_contents ( $file ) );
}
}
} else if (is_file ( $source ) === true) {
$zip->addFromString ( basename ( $source ), file_get_contents ( $source ) );
}
$zipSuccess = $zip->close ();
if($zipSuccess){
$response = [
'tpodResponse' => true,
'message' => Messages::ZIP_CREATED_SUCCESSFULLY . $destination
];
}
else{
$response = [
'tpodResponse' => false,
'message' => Messages::ZIP_CREATED_ERROR
];
}
return $response;
}
代替addString方法也试过下面的代码
$relativePath = strstr($file,'data');
$zip->addFile($file,$relativePath);
--------------------------------------
$relativePath = strstr($source,'data');
$zip->addFile($source,$relativePath);
但这仍然没有给出理想的结构。
请帮忙