首页 > 解决方案 > 文件存在但收到无法打开流的警告:没有这样的文件或目录

问题描述

<?php
$arch_filename = "myzipx.zip";
$dest_dir = "./dest";
if (!is_dir($dest_dir)) {
    if (!mkdir($dest_dir, 0755, true))
        die("failed to make directory $dest_dir\n");
}
$zip = new ZipArchive;
if (!$zip->open($arch_filename))
    die("failed to open $arch_filename");

for ($i = 0; $i < $zip->numFiles; ++$i) {
    $path = $zip->getNameIndex($i);
    $ext = pathinfo($path, PATHINFO_EXTENSION);
    if (!preg_match('/(?:pdf)/i', $ext))
        continue;
    $dest_basename = pathinfo($path, PATHINFO_BASENAME);
    echo $path, PHP_EOL;

    copy("$path", "$dest_dir/{$dest_basename}");
}

$zip->close();
?>

发生了一件奇怪的事情,因为这段代码只工作了 15 分钟,现在抛出警告

(!)警告:复制(myzipx/x/x.pdf):无法打开流:第 21 行的 C:\wamp64\www\zip_ex\x\zip_img.php 中没有这样的文件或目录

但该文件存在并回显正确的文件名。不明白似乎是什么问题..任何帮助表示赞赏。

标签: phpcopyzip

解决方案


你的尝试copy()是正确的。与ZipArchive::extractTo()(提取并在目标中创建子文件夹)不同,该方法copy()只是将指定文件从存档复制/提取到目标。

这个例子应该工作:

$archive = "testarchive.zip";
$dest_dir = "./dest";
if (!is_dir($dest_dir)) {
    if (!mkdir($dest_dir, 0755, true)) die("failed to make directory $dest_dir\n");
}
$zip = new ZipArchive;
if (!$zip->open($archive)) die("failed to open $archive");

for($i = 0; $i < $zip->numFiles; $i++) {
    $file_name = $zip->getNameIndex($i);
    $file_info = pathinfo($file_name);
    $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
    if (preg_match('/pdf/i', $file_ext)) {
        copy("zip://".$archive."#".$file_name, $dest_dir.'/'.$file_info['basename']);
    }
}                  
$zip->close();

测试档案结构:

xxxxx@xxxxxx:~/Documents$ tree testarchive
testarchive
└── test
    └── blubb
        └── test.pdf

然后将该文件夹testarchive压缩为testarchive.zip.

运行上面的代码后:

xxxxx@xxxxxx:~/Documents$ tree dest
dest
└── test.pdf


推荐阅读