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

Source: Internet
Author: User
Tags ord sprintf

1. iconv () Introduction

The Iconv function converts a well-known character set file to another known character set file. For example, convert from GB2312 to UTF-8.

The Iconv function is built into the PHP5 and the GB character set is turned on by default.

2. iconv () error

Iconv error when converting the character "-" to gb2312, the workaround is to add "//ignore" after the encoding to be transferred, that is, after the second parameter of the ICONV function. As follows:

Iconv ("UTF-8", "Gb2312//ignore", $data)

Ignore means ignoring errors at the time of conversion, and if there is no ignore argument, all strings after that character cannot be saved.
3. iconv ()Example 1:
<?php
echo $str = ' Hello, here is coffee! ';
echo ' <br/> ';
Echo Iconv(' GB2312 ', ' UTF-8 ', $str); To transfer the encoding of a string from GB2312 to UTF-8
echo ' <br/> ';
Echo Iconv_substr($STR, 1, 1, ' UTF-8 '); Intercept by number of characters rather than bytes
Print_r ( iconv_get_encoding()); Get the current page encoding information
Echo Iconv_strlen($str, ' UTF-8 '); Gets the string length of the set encoding
?>
Example 2: If your PHP file is UTF-8 encoded, then the following code can be correctly output: <?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, then the following code can work: <?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; ?> above, the contents of the program output are:%E6%88%91%E7%88%B1%E7%99%BE%E5%BA%A6

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

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.