Method: 1. Use iconv function, syntax "iconv(original character type, 'UTF-8', string)"; 2. Use mb_convert_encoding function, syntax "mb_convert_encoding(string, 'UTF-8" ', original character type)".
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
1. Use the iconv() functioniconv
function can convert a known character set file into another known character set file. For example: Convert from GB2312
to UTF-8
. iconv will make an error when converting the characters "—" to "gb2312
". The solution is to add "//IGNORE
" after the encoding that needs to be converted, which is the second iconv function. parameters. As follows:
iconv("UTF-8", "GB2312//IGNORE", $data)
ignore
means to ignore errors during conversion. Without the ignore
parameter, all strings following this character cannot be saved.
<?php echo $str= ‘你好,这里是卖咖啡!'; echo '<br />'; echo iconv('GB2312', 'UTF-8', $str); //将字符串的编码从GB2312转到UTF-8 ?>
2. Use "mb_convert_encoding" to convert the string into the UTF8 character set
When using mb_convert_encoding
, you must first know the character encoding. If If the encoding is wrong, the characters will be garbled. Use mb_detect_encoding
to automatically identify the string encoding and convert it to the international standard encoding utf-8 encoding.
<?php $encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5','LATIN1')); if($encode != 'UTF-8'){ $name = mb_convert_encoding($name, 'UTF-8', $encode); } ?>
Recommended tutorial: php video tutorial
The above is the detailed content of How to convert string to utf8 format in php. For more information, please follow other related articles on the PHP Chinese website!