Home > php教程 > php手册 > php识别中文编码并自动转换为UTF

php识别中文编码并自动转换为UTF

WBOY
Release: 2016-05-25 16:40:36
Original
1082 people have browsed it

下面整理了php识别中文编码并自动转换为UTF-8几个例子,这些例子非常的不错,希望对各位有帮助.

php自动识别编码,若里面有中文的话,将其转换为UTF-8就最好了,因为中文在Gbk编辑情况情况下,有可能会乱码,这个和客户端和服务端编码都有关系,为了避免乱码,我们可以使用下面的函数将其自动转换为UTF8国际标准编码,代码如下:

<?php 
function characet($data){ 
  if( !emptyempty($data) ){ 
    $fileType = mb_detect_encoding()($data , array(&#39;UTF-8&#39;,&#39;GBK&#39;,&#39;LATIN1&#39;,&#39;BIG5&#39;)) ; 
    if( $fileType != &#39;UTF-8&#39;){ 
      $data = mb_convert_encoding($data ,&#39;utf-8&#39; , $fileType); 
    }
  } 
  return $data; 
} 
?>
Copy after login

补充:文件编码转换,代码如下:

$temstr=file_get_contents($path);  
$encode   = mb_detect_encoding($temstr,"ASCII,UTF-8,CP936,EUC-CN,BIG-5,EUC-TW");     
$temstr=mb_convert_encoding($temstr,   "CP936",   $encode);
Copy after login

例子,代码如下:

<?php    
$f=fopen("test.txt", "wb");    
$text=utf8_encode("a!");    
//先用函数utf8_encode将所需写入的数据变成UTF编码格式。    
$text="\\xEF\\xBB\\xBF".$text;    
//"\\xEF\\xBB\\xBF",这串字符不可缺少,生成的文件将成为UTF-8格式,否则依然是ANSI格式。    
fputs($f, $text);    
//写入。    
fclose($f);    
?>
Copy after login


永久链接:

转载随意!带上文章地址吧。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template