encoding - 用PHP如何检测一个ZIP包内的文件是在何种编码的系统下创建的
PHP中文网
PHP中文网 2017-04-10 14:25:17
[PHP讨论组]

事情起源于在WIN下创建的zip放到linux下解压时,中文路径和文件名会出现乱码,于是动手写了个脚本转换zip内文件名的代码。但是,如果是在日语、韩语或者繁体字WIN系统下建立的zip,由于不知道原始编码格式,导致无法转码。
怎么解。。。

PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(4)
PHPz

LZ 的 id 看着眼熟 ... 这么多年了还在问这个等级的问题 ... 你也不容易啊你 ...

<?php
/* well ... prepare our zip file ... */
$zip = new ZipArchive;
$res = $zip->open( '/path/to/your.zip' );

/* can not open ..? are you kidding me ..? */
if ( true !== $res )
    throw new Exception( 'Can Not Open Zip File / ' . $res );

/* default value of file encoding ... */
$encoding = 'EMTPY';

/* controller ... change this if mb_detect_encoding return wrong answer ... */
$controller = null;

/* get file list ... */
for ( $i = 0; $i < $zip->numFiles; ++ $i ) {

    /* get file encoding ... */
    $encoding = mb_detect_encoding( $zip->getNameIndex( $i ), $controller );

    /* we do not need english named files ... */
    if ( 'ASCII' !== $encoding ) break;

}

/* clean table ... */
$zip->close();

/* simply output ... */
echo $encoding;

代码就是这样了 ... 根据文件名来判断系统 ...

简体中文的 windows 会返回 EUC-CN ... 繁体中文我猜测应该是 EUC-TW 或者 BIG5 ...

Linux 和 MacOS 都是 UTF-8 ... 纯英文的文件就别捣乱了 ...

阿神

@Ven 就是文件名的编码吧,稍微改了下楼上的代码,我的系统是linux,所以要把非UTF-8的重新编码为UTF-8

<?php
function detect_encoding($zipfile_name){
    $zip = new ZipArchive;
    $res = $zip->open($zipfile_name);
    if(true !== $res)
        throw new Exception('Can Not Open Zip File '.$res);

    $encoding = "UTF-8";
    $controller = array("ASCII","UTF-8", "GB2312", "GBK", "BIG5");

    for($i = 0; $i < $zip->numFiles; ++ $i){
        $entry = $zip->getNameIndex($i);
        $encoding = mb_detect_encoding($entry, $controller);
        if( "UTF-8" !== $encoding)
            $entry = iconv($encoding, "UTF-8", $entry);
        echo $entry." ---> ".$encoding.chr(10);
    }
    $zip->close();
}
detect_encoding($argv[1]);
?>
巴扎黑

正确答案见@Sunyanzi 的回答,这里再补充一些。
由于Windows系统的历史原因,部分压缩软件生成的zip包,在用mb_detect_encoding()检查文件名的编码时,会得到类似“CP936”这样的结果。我当时在这里被搞晕了,以为函数没能正确检测到编码。实际上CP936是微软自己的一套标准,基本上等于GBK。
而关于其他的“CP***”的编码对应关系,或许可以参看这篇文章:Windows代码页

怪我咯

ZIP格式,似乎文件名没有编码这一说。
至于你说的解压缩出现乱码,这是解压缩软件的问题……

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号