php中fopen不能创建中文文件名文件的问题

来源:互联网 发布:js 空白处点击事件 编辑:程序博客网 时间:2024/05/08 15:36

之前网页的chartset用的是utf-8,文件也用utf-8,然后用fopen()创建一个中文文件名的文件时问题就出来了,文件名都是乱码!

查看了很多文档试了不少方法都解决不了,本来想着用别的方法绕过这个问题,忽然脑子里闪过Windows默认的文字编码是ansi,然后再baidu了一下,证实了这点,所以我的网页也应该是ansi编码才能使创建的文件名不会是乱码。

接着就着手验证,把网页都用ansi保存,去掉chartset语句,果然ok了,但是网页的内容就成乱码了,后来想起,这个网页还include了别的网页,把include的网页也改成ansi保存,哈哈万事ok

编程这个工作真的很靠积累,如果我以前没看过Windows默认编码是ansi,那这个问题就不知何年何月才能解决了

ps:<meta content="text/html; charset=utf-8" http-equiv="Content-type"> 这个meta标记一定要放在<title></title>之前才有效的

后来又想到了一个更好的解决方法,网页还是用utf-8编码和保存,只是fopen()里的文件名参数单独给它编下码就行,php有iconv()这个改换编码的程序,把utf-8转成gb2312就可以避免中文文件名为乱码了

 

==================================

test.htm

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>标题:{title}</title>
</head>
<body>
<b>此新闻的内容:</b>{content}
</body>
</html>

 

 

 

test.php

 

<?php

    //实际应用中很可能是查询数据库取内容。
    $rows = array(array("替换标题1","替换内容1"),array("替换标题2","替换内容2"));
    $filename = "tmp.htm";
    foreach($rows as $id => $val){
        $title = $val[0];
        $content = $val[1];
        $pagename = "测试".$id.".html";
        //对文件名的编码,避免中文文件名乱码
        $pagename = iconv("UTF-8", "GBK", $pagename);
       
        //读取模板
        $tmpfile = fopen($filename,"r");
        $string = fread($tmpfile,filesize($filename));
        $string = str_replace("{title}",$title,$string);
        $string = str_replace("{content}",$content,$string);
        fclose($tmpfile);
        //写新文件
        $newpage = fopen($pagename,"w");
        fwrite($newpage,$string);
        fclose($newpage);
       
    }
    echo "创建成功!";
?>

 

 

转自:http://blog.csdn.net/lovewqww/archive/2008/03/20/2200949.aspx

原创粉丝点击