php中文文件名输出乱码问题_PHP中文文件名输出乱码解决方法

更新时间:2019-06-17    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

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

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

 代码如下

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

例子

 代码如下

//执行创建中文名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("中文");

例子

 代码如下

$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.bbyears.com/jiaocheng/54588.html