如何检查zip文件中是否存在某个文件

7
我有一个zip压缩包,解压后需要检查其中是否存在moduleConfig.xml文件。我该如何实现?
我尝试过以下方法:
$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
    if(file_exists($zip->getFromName('moduleConfig.xml')))
    {
        echo "Config exists";
        // Do somthing
    }
}
else {
    echo 'Failed code:'. $res;
}

你尝试了这个,但它做了什么反而? - dbf
我尝试了这个和那个,但都不起作用。我不明白你的问题。 - Ivan
3个回答

11

应该是这样的:

$zip = new ZipArchive();
if($zip->open('test.zip') === TRUE )
{
    if ($zip->locateName('moduleConfig.xml') !== false)
    {
    echo "Config exists";
    }
}
else {
    echo 'Failed code:'. $res;
}

注意:您应该使用 !== false 进行检查,因为当文件存在时它可能会返回 0。所以 if ( $zip->locateName('file.xml') ) {...} 不正确地工作。更多信息 - Hector

7

尝试:

if ($zip->locateName('moduleConfig.xml') !== false)
{
    echo "Config exists";
}

0
您可以使用getFromName来实现此操作。
        $zip = new ZipArchive();

        if($zip->open('test.zip') === TRUE )
        {
            if($zip->getFromName('moduleConfig.xml') != false)
            {
                echo "Config exists";
                // Do somthing
            }
        }
        else {
            echo 'Failed code:'. $res;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接