ZIP 文件夹 whitou 根


ZIP folder whitou root

我有一个脚本,当压缩文件夹"output"的内容时会调用,但是当我尝试加载位于文件夹 www/projectname 中的文件夹"Outpup"的内容时,我压缩了根目录 C:'' 中的文件

我的脚本

$rootpath="./Output";
$destinazione="./Output/lista.zip";
 Zip($rootpath,$destinazione);

函数 邮编

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('''', '/', realpath($source));
    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file)
        {
            $file = str_replace('''', '/', $file);
            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;
            $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));
    }
    return $zip->close();
}

只需要压缩文件夹"output"的内容,但在zip中我得到了以下嵌套文件夹

c:'
└─ Program Files (x86)
 └─  www
  └─ Separalista
   └─output
     ├─ folder1
     │ └─ file.csv
     └─ folder2 
       └─ file.csv

我想在zip文件中只找到子文件夹"输出"

output
  ├─ folder1
  │  └─ file.csv
  └─ folder2 
     └─ file.csv

感谢大家

问题是 - 你的工作目录,在你的$rootpath中用点表示,可以是任何东西,没有什么使它成为脚本自己的目录。要将工作目录更改为脚本的目录,请使用:

chdir( dirname ( realpath ( __FILE__ ) ) );

或者,在 PHP 5.3.0 或更高版本中,只需

chdir( __DIR__ );

在脚本的开头。

如果这不起作用,则必须进行更深层次的更改。将脚本的路径直接附加到包含目录的变量,如下所示:

$rootpath = __DIR__ . '/Output';
$destinazione = $rootpath . '/lista.zip';

假设您的文件位于项目的根目录中,上面应该可以工作。如果没有,请相应地修改$rootpath。在 PHP 5.3.0 之前的版本中,使用 dirname ( realpath ( __FILE__ ) ) 代替 __DIR__