Home >Backend Development >PHP Problem >How to convert php to encoding

How to convert php to encoding

藏色散人
藏色散人Original
2020-11-05 09:17:583553browse

How to implement PHP encoding conversion: 1. Use the iconv function to convert the target encoding, with syntax such as "iconv('GBK','UTF-8′,$instr);"; 2. Convert the encoding through the mb_convert_encoding function .

How to convert php to encoding

Recommended: "PHP Video Tutorial"

When using PHP to process strings, we often encounter The problem of character encoding conversion, have you ever encountered iconv conversion failure?

When I discovered the problem, I searched online and found that iconv had a bug. It would not be able to convert some rare words. Of course, when configuring the second parameter, you can make up for the default defects a little, so as not to cause problems. If it cannot be converted, it is truncated. The usage is as follows

iconv(“UTF-8″,”GB2312//IGNORE”,$data)  ;

In this way, when the conversion of rare words fails, it will ignore the failure and continue to convert the following content. This is a way to solve the problem, but in order to ensure the success rate of conversion , we can use another conversion function (mb_convert_encoding). According to the information online, this function is not very efficient. In addition, this function can also omit the third parameter and automatically identify the content encoding. However, it is best not to use it, as it affects efficiency and also It should be noted that the order of mb_convert_encoding and iconv parameters is different, so be sure to pay attention.

Attached are the simple usage of two functions:

iconv

string iconv ( string $in_charset , string $out_charset , string $str )

The first parameter: the original encoding of the content

Two parameters: target encoding

The third parameter: the string to be converted

The function returns the string

<?php
$instr = ‘测试’;
// GBK转UTF-8
$outstr = iconv(‘GBK’,&#39;UTF-8′,$instr);
?>

mb_convert_encoding

string mb_convert_encoding ( string $str , string $to_encoding [, mixed $from_encoding ] )

The first parameter: the string to be processed

The second parameter: the target encoding

The third parameter: the original encoding of the content

<?php
$instr = &#39;测试&#39;;
// GBK转UTF-8
$outstr = mb_convert_encoding($instr,&#39;UTF-8&#39;,&#39;GBK&#39;,);
?>

Personal suggestion When it comes to transcoding problems, it is safer to use mb_convert_encoding.

The above is the detailed content of How to convert php to encoding. 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