Home > Article > Backend Development > How to convert character encoding to utf8 in php
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.
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); } }
Description:
mb_detect_encoding() function is used to detect the encoding of characters.
mb_detect_encoding ( string $str , mixed $encoding_list = mb_detect_order())
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] )
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"); ?>
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");
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!