PHP无法从ZIP归档提取指定文件 求单个文件提取示例
单个文件从ZIP提取的PHP示例代码
问题背景
提取ZIP内指定文件时触发错误:
Warning: copy(zip://upload/myzip-file.zip#myzip-file/file_001.csv): Failed to open stream: operation failed in {code line}
已知条件:
myzip-file.zip存于同级upload文件夹,脚本可读取ZIP内容,但无法通过copy+zip://协议提取文件- ZIP内包含
myzip-file子文件夹,需提取文件到同级my-path且不生成子文件夹
示例代码
方法1:读取文件内容直接写入
$zipPath = 'upload/myzip-file.zip'; // ZIP内目标文件的完整路径(包含内部子文件夹) $targetZipFile = 'myzip-file/file_001.csv'; // 输出路径(直接指定文件名,避免子文件夹) $outputFile = 'my-path/file_001.csv'; $zip = new ZipArchive; if ($zip->open($zipPath) === true) { // 读取ZIP内指定文件的内容 $content = $zip->getFromName($targetZipFile); if ($content !== false) { // 将内容写入目标文件 file_put_contents($outputFile, $content); } $zip->close(); }
方法2:提取后调整文件位置
$zipPath = 'upload/myzip-file.zip'; $targetZipFile = 'myzip-file/file_001.csv'; $outputFile = 'my-path/file_001.csv'; $zip = new ZipArchive; if ($zip->open($zipPath) === true) { // 提取指定文件到输出目录的临时路径(会保留ZIP内的子文件夹结构) if ($zip->extractTo('my-path', $targetZipFile)) { $tempFilePath = 'my-path/' . $targetZipFile; // 将文件移动到最终位置 rename($tempFilePath, $outputFile); // 删除临时生成的空文件夹 rmdir('my-path/myzip-file'); } $zip->close(); }
内容的提问来源于stack exchange,提问作者PHP Avenger
相关产品推荐
相关产品推荐

