首页 > 解决方案 > PHP ZipArchive::close 返回 false

问题描述

我正在尝试从 PHP 更改一些 docx 变量。但是在保存步骤总是错误的。

我尝试在 composer.json 中对目录、php-zip 扩展名、“ext-zip”:“*”设置 777 权限。

我的代码:

$zip = new \ZipArchive();

        $wordDoc = $this->container->get('kernel')->getRootDir() . '/../file.docx';
        $fileToModify = 'word/document.xml';

        if ($zip->open($wordDoc, ZipArchive::CREATE) === TRUE) {
            $oldContents = $zip->getFromName($fileToModify);

            $newContents = str_replace(' MERGEFIELD __FIRSTNAME__ ', 'NEWNAME', $oldContents);

            $zip->deleteName($fileToModify);

            $zip->addFromString($fileToModify, $newContents);

            if ($zip->close()) {
                echo "Done.";
            }
            else {
                echo 'fail';exit();
            }
        }

启用 php -m zip:

zip,
zlib

php --ini zip 启用:

/etc/php7/conf.d/00_zip.ini,

我希望覆盖旧文件并使用新值获取新文件,但总是出错$zip->close();

标签: phpzipdocxziparchive

解决方案


解决了。在工作之前需要创建原始文件的副本。

$original = $this->container->get('kernel')->getRootDir() . '/../file.docx';
if (copy($original, $this->container->get('kernel')->getRootDir() . '/../temp/newFile.docx')) {
      $tempFile = $this->container->get('kernel')->getRootDir() . '/../temp/newFile.docx';
}

推荐阅读