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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。