php处理中文编码老是有问题,这是编码的问题,可以将txt文件另存为UTF-8的编码再处理;
参考如下:
function file_utf8($filepath){
$f_contents= file_get_contents($filepath);
$encoding = mb_detect_encoding($f_contents, array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
$content_u="";
$handle=fopen($filepath,"r");
if ($handle){
while (!feof($handle)) {
$buffer= fgets($handle);
if ($encoding != false) {
if (mb_detect_encoding($buffer)!='UTF-8'){
$buffer = iconv($encoding, 'UTF-8', $buffer);
}
}else{
$buffer = mb_convert_encoding ( $buffer, 'UTF-8','Unicode');
}
$content_u.=$buffer;
}
fclose($handle);
return $info=array('status'=>1,'message'=>$content_u);
}else{
return $info=array('status'=>0,'message'=>'打开文件失败');
}
}
首先看你网页编码是什么,一般本地计算机都是GB2312编码 如果你使用其它可能就会产生乱码
显然你的字符集没有设置好~
$arr = file("school.txt");
foreach ($arr as $value)
{
$search = array("[","]");
$replace = array("","");
//替换
$string = str_replace($search, $replace, iconv("utf-8","GB2312",$value));
//附加分号和换行
$string = $string.";"."\r\n";
//写入文件
$fp = fopen("schools.txt", "ab");
if(!$fp)
{
echo "文件打开错误";
exit;
}
fwrite($fp,$string);
fclose($fp);
}
字符编码不对