What is the usage of iconv in PHP?
In PHP, the function iconv() is used for converting between character sets. Its basic usage is as follows:
Convert the string from one character encoding to another.
Explanation of parameters:
- $in_charset: Character set of the input string.
- $out_charset: character set of the output string.
- $str: The string to be converted.
Return value:
Return the transformed string.
例子:例如
$str = "你好,世界!";
$convertedStr = iconv("UTF-8", "GBK", $str);
echo $convertedStr; // 输出:浣犲ソ锛堟垜鍥�
$convertedStr2 = iconv("GBK", "UTF-8", $convertedStr);
echo $convertedStr2; // 输出:你好,世界!
In the examples above, the UTF-8 encoded string is first converted to a GBK encoded string, and then the converted string is converted back to UTF-8 encoding.
Important points to note:
- When dealing with character set conversions, errors may occur in the iconv() function, which can be ignored by setting the error_reporting() function.
- If there are characters that cannot be converted during the conversion process, the iconv() function will by default replace those characters with a question mark (?). Setting the fourth parameter of the iconv() function allows for specifying a different way to replace these characters.
For further information on how to use and the parameters of the iconv() function, please refer to the official PHP documentation.