首页 > php开发 > PHP中文文件名输出乱码解决方法

PHP中文文件名输出乱码解决方法

在php中碰到中文文件名乱码一般都是初学者了,因为我们一般不会使用中文文名了,因为大家都知道php对中文支持不友好,那么我们要如何解决php中文文件名乱码问题呢?下面小编给各位整理了一些方法,下面一起来看看.

原因是编码问题,所以要转码,用户PHP里面的 iconv 函数就可以解决:

iconv("当前使用的编码如:utf-8","要转换的编码如:GB2312","文件名");

php实例代码如下:

$file_name="我的文件.jpg"; 
$file_name=iconv("utf-8","gb2312",$file_name);   //解决中文乱码问题 
echo '$file_name';

例子: 

<?php 
//执行创建中文名html文件 
file_put_contents(PHPCMS_PATH.'test/'.iconv('UTF-8', 'GBK', '中文名').'.html', 'xxxxxxxxxxx');

另一种解决中文乱码问题在于,代码如下:

$sFileName = "sda.php"; 
$sOriginalFileName = $sFileName; 
$sExtension = s str($sFileName, (strrpos($sFileName, '.') + 1));//找到扩展名 
$sExtension = strtolower($sExtension); 
$sFileName = date("YmdHis").rand(100, 200).".".$sExtension; 
//这样就是我们的新文件名了,全数字的不会有乱码了。

我们还可以使用urlencode来进行编译,如:urlencode('中文');例子代码如下:

<?php
$file = "/tmp/中文名.tar.gz";
$filename = basename($file);
header("Content-type: application/octet-stream");
//处理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = urlencode($filename);
$encoded_filename = str_replace("+", "%20", $encoded_filename);
if (preg_match("/MSIE/", $ua)) {
    header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
    header("Content-Disposition: attachment; filename*=\"utf8\"" . $filename . '"');
} else {
    header('Content-Disposition: attachment; filename="' . $filename . '"');
}
header('Content-Disposition: attachment; filename="' . $filename . '"');
header("Content-Length: " . filesize($file));
readfile($file);

注意:我的服务器是windows xp、apache,估计xp字符集是gbk,因为我的php代码保存为utf-8格式的,在给文件名命名时会出现乱码的情况,所以可以用iconv()函数将原本的utf-8格式的文件名转换为gbk格式的.


本文地址:http://www.phprm.com/develop/fs5828.html

转载随意,但请附上文章地址:-)

标签:php中文乱码 php乱码方法

相关文章

发表留言