PHP uses iconv to convert a string from GBK to UTF8 Character Set

Source: Internet
Author: User

1. iconv () Introduction
The iconv function can convert a known character set file to another known character set file. Example: Convert from GB2312 to UTF-8.
The iconv function is built in php5. The GB character set is enabled by default.
2. iconv () Error
Iconv will encounter an error when converting the characters "-" To gb2312. The solution is to add "// IGNORE" after the encoding to be converted, that is, after the second parameter of the iconv function:
Copy codeThe Code is as follows:
Iconv ("UTF-8", "GB2312 // IGNORE", $ data)

Ignore indicates that the conversion error is ignored. Without the ignore parameter, all strings after this character cannot be saved.
3. iconv () Example
Example 1:
Copy codeThe Code is as follows:
<? Php
Echo $ str = 'Hi, it's coffee sale! ';
Echo '<br/> ';
Echo iconv ('gb2312', 'utf-8', $ str); // encode the string from GB2312 to UTF-8
Echo '<br/> ';
Echo iconv_substr ($ str, 1, 1, 'utf-8'); // truncate by number of characters rather than bytes
Print_r (iconv_get_encoding (); // obtain the encoding information of the current page.
Echo iconv_strlen ($ str, 'utf-8'); // you can specify the length of the encoded string.
?>

Example 2:
If your php file is UTF-8 encoded, the following code can be output correctly:
Copy codeThe Code is as follows:
<? Php
$ Str = 'I love Baidu ';
$ Utf = '';
For ($ I = 0; $ I <strlen ($ str); $ I ++) $ utf. = sprintf ("% 02X", ord (substr ($ str, $ I, 1 )));
Echo $ utf;
?>

If your php file is GB, the following code can work:
Copy codeThe Code is as follows:
<? Php
$ Str = 'I love Baidu ';
$ Str = iconv ("GBK", "UTF-8", $ str );
$ Utf = '';
For ($ I = 0; $ I <strlen ($ str); $ I ++) $ utf. = sprintf ("% 02X", ord (substr ($ str, $ I, 1 )));
Echo $ utf;
?>

In the above cases, the program outputs the following content:
% E6 % 88% 91% E7 % 88% B1 % E7 % 99% BE % E5 % BA % A6

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.