Home>Article>Backend Development> What function is used to convert php gbk to utf8

What function is used to convert php gbk to utf8

藏色散人
藏色散人 Original
2021-12-15 10:41:19 1779browse

In PHP, you can use the iconv function to convert gbk to utf8. This function can convert a known character set file into another known character set file. The conversion syntax is such as "iconv(" GB2312","UTF-8",$data);".

What function is used to convert php gbk to utf8

#The operating environment of this article: Windows 7 system, PHP version 7.4, Dell G3 computer.

php What function is used to convert gbk to utf8?

Function: PHP converts a string from GBK to UTF8 character set iconv

1.iconv()Introduction

The iconv function can Convert a knowncharacter setfileinto another known character set file. For example: Convert from GB2312 to UTF-8.

The iconv function is built in php5, and the GB character set is turned on by default.


2.

iconv()Error

Iconv will make an error when converting the character "-" to gb2312. The solution is to add the encoding that needs to be converted. Add "

//IGNORE", which is after the second parameter of the iconv function. As follows:

iconv("UTF-8", "GB2312//IGNORE", $data)

ignore means to ignore errors during conversion, if there are no ignore parameter, all strings following this character cannot be saved.


3.

iconv()Example

Example 1:



echo $str= 'Hello, we sell coffee here!';
 echo '
';
 echoiconv('GB2312', 'UTF-8', $str); //Convert the string encoding from GB2312 to UTF-8
echo '
';
echoiconv_substr($str, 1, 1, 'UTF-8'); //Truncate by the number of characters instead of bytes
print_r(iconv_get_encoding()); //Get the current page encoding information
echoiconv_strlen($str, 'UTF-8'); // Get the string length of the set encoding
 ?>

Example 2:

If your PHP file is UTF-8 encoding, then the following code can be output correctly:

  $str='I love Baidu';

## $utf='';

for ($i=0;$i

## echo $utf;

## ?>

If your PHP file is GB, then the following code can work:

## $str='I love Baidu';

##  $str=iconv("GBK", "UTF-8", $str);

  $utf='';

#  for ($i=0;$i

 echo $utf;

## ?>

In the above case, the program output is:

I love Baidu

Recommended Study: "PHP Video Tutorial

"

The above is the detailed content of What function is used to convert php gbk to utf8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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