PHP:如何创建unicode文件名

T-R*_*onX 7 php unicode filenames

我正在尝试在文件名中创建带有Unicode字符的文件.我不太清楚我应该使用什么编码,或者它是否可能.

我有这个文件,以latin1编码保存:

$h = fopen("unicode_♫.txt", 'w');
fclose($h);
Run Code Online (Sandbox Code Playgroud)

在UTF-8中,这将解码为'unicode_♫.txt'.它将latin1版本写入磁盘(很明显?).我需要它保存,因为它会出现UTF-8解码.我也试过用UTF-16编码它,但那也不行.

我正在使用PHP 5.2,并希望这与NTFS,ext3和ext4一起使用.

如何才能做到这一点?

Art*_*cto 10

它目前无法在Windows上完成(可能PHP 5.4将支持此方案).在PHP中,您只能使用Windows set代码页编写文件名.如果代码页不包含该字符?,则无法使用它.更糟糕的是,如果Windows上的文件在其文件名中包含此类字符,则您将无法访问它.

在Linux中,至少在ext*中,它是一个不同的故事.您可以使用您想要的任何文件名,操作系统不关心编码.因此,如果您始终使用UTF-8中的文件名,那么您应该没问题.但是,排除了UTF-16,因为文件名不能包含值为0的字节.


小智 5

对我来说,下面的代码适用于Win7/ntfs,Apache 2.2.21.0和PHP 5.3.8.0:

<?php
// this source file is utf-8 encoded

$fileContent = "Content of my file which contains Turkish characters such as ??????";

$dirName = 'Dirname with utf-8 chars such as ??????';
$fileName = 'Filename with utf-8 chars such as ??????';

// converting encodings of names from utf-8 to iso-8859-9 (Turkish)
$encodedDirName = iconv("UTF-8", "ISO-8859-9//TRANSLIT", $dirName);
$encodedFileName = iconv("UTF-8", "ISO-8859-9//TRANSLIT", $fileName);

mkdir($encodedDirName);
file_put_contents("$encodedDirName/$encodedFileName.txt", $fileContent);
Run Code Online (Sandbox Code Playgroud)

你可以为打开文件做同样的事情:

<?php
$fileName = "Filename with utf-8 chars such as ???";
$fileContent = file_get_contents(iconv("UTF-8", "ISO-8859-9//TRANSLIT", "$fileName.txt"));
print $fileContent;
Run Code Online (Sandbox Code Playgroud)