How to convert character encoding to utf8 in php

青灯夜游
Release: 2023-03-08 09:48:01
Original
7860 people have browsed it

In PHP, you can first use the mb_detect_encoding() function to obtain the original encoding of the character; then use "mb_convert_encoding("specified character", "UTF-8", "original encoding of the character")" To convert the character encoding to utf8.

How to convert character encoding to utf8 in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts character encoding to utf8

function strToUtf8($str){
    $encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
    if($encode == 'UTF-8'){
        return $str;
    }else{
        return mb_convert_encoding($str, 'UTF-8', $encode);
    }
}
Copy after login

Description:

mb_detect_encoding() function is used to detect the encoding of characters.

mb_detect_encoding ( string $str , mixed $encoding_list = mb_detect_order())
Copy after login
  • str: ​​The string to be checked.

  • encoding_list: is a character encoding list. The encoding order can be specified by an array or a comma-separated list of strings.

[Recommended study: "PHP Video Tutorial"]

mb_convert_encoding() function converts the encoding of characters

mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )
Copy after login
  • string str String that needs encoding conversion;

  • string to_encoding specifies the conversion to a certain encoding, such as: gb2312, gbk, utf-8, etc.;

Example:

1. Convert GBK encoded string to UTF-8 encoded string;

<?php  
header("content-Type: text/html; charset=Utf-8");  
echo mb_convert_encoding("你是我的好朋友", "UTF-8", "GBK");  
?>
Copy after login

2. Convert UTF-8 encoded string Into GB2312 encoded string

// 注意将此文件存盘成 utf-8 编码格式文件再测试
<?php  
header("content-Type: text/html; charset=gb2312");  
echo mb_convert_encoding("你是我的好朋友", "gb312", "utf-8");
Copy after login

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of How to convert character encoding to utf8 in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template