dtng5978 2014-02-27 12:27
浏览 100
已采纳

获取UTF-8文件名以使用PHP ZipArchive

I have a file that I want to add to a Zip with PHP, which is encoded in UTF-8. Here is the filename: 'µ漢字ääÖÅ.txt'.

Now, to get this file even to save to the filesystem I had to do this:

$filename = "µ漢字ääÖÅ.txt";
$codepage = 'Windows-' . trim(strstr(setlocale(LC_CTYPE, 0), '.'), '.');
$encoded_filename = iconv('UTF-8', $codepage.'//IGNORE', $filename);
file_put_contents($encoded_filename, "text");

Now when I want to add the file to the ziparchive I use the following code:

$zip = new \ZipArchive();
$zip->open('test.zip', \ZIPARCHIVE::CREATE);
$zip->addFile($encoded_filename, $encoded_filename);
$zip->close();

Which results in a zip file containing the file name 'ÁõõÍ+.txt'. How do I get it to save correctly?

  • 写回答

1条回答 默认 最新

  • doujiong2533 2014-02-27 14:40
    关注

    I have found an answer (sort of). In the example above $encoded_filename was changed from UTF-8 to Windows-1252 encoding to save to the filesystem. I have no idea why but Windows-1252 works when saving directly to the filesystem but NOT when saving to a zip using ZipArchive.

    To fix this I had to encode the $filename yet again to a different encoding, CP858.

    Example:

    $filename = "µ漢字ääÖÅ.txt";
    
    //encode to windows-1252 to save to the filesystem
    $encoded_filename = iconv("UTF-8","Windows-1252//IGNORE",$filename);
    file_put_contents($encoded_filename, "text");
    
    //put in a zip file
    $zip = new \ZipArchive();
    $zip->open('test.zip', \ZIPARCHIVE::CREATE);
    //encode as CP858 to save into zip file
    $zip->addFile($encoded_filename, iconv("UTF-8", "CP858//IGNORE", $filename));
    $zip->close();
    

    In the above example it still doesn't handle the Japanese characters in the file name, but at least it handles European characters which will have to do for the time being.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现