获取UTF-8文件名以与PHP ZipArchive一起使用 [英] Getting UTF-8 filenames to work with PHP ZipArchive

查看:92
本文介绍了获取UTF-8文件名以与PHP ZipArchive一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要使用PHP添加到Zip的文件,该文件以UTF-8编码.这是文件名:"µ汉字ääÖÖ.txt".

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");

现在,当我要将文件添加到ziparchive时,我使用以下代码:

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();

这将生成一个包含文件名ÁõõÍ+ .txt"的zip文件.如何正确保存它?

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

推荐答案

我找到了答案(有点).在上面的示例中,$encoded_filename从UTF-8更改为Windows-1252编码,以保存到文件系统.我不知道为什么,但是Windows-1252在直接保存到文件系统时可以工作,而在使用ZipArchive保存到zip时不能工作.

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.

要解决此问题,我不得不再次将$ filename编码为另一种编码CP858.

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

示例:

$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.

这篇关于获取UTF-8文件名以与PHP ZipArchive一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆