Home >Backend Development >PHP Tutorial >PHP string encoding conversion

PHP string encoding conversion

巴扎黑
巴扎黑Original
2016-11-22 11:03:531341browse

In web development, string encoding must be converted frequently. A little carelessness may result in garbled characters. So it can be said that the encoding problem is a big problem. After some searching, I found a piece of code for string encoding conversion, and then simply packaged it, making it more convenient to use.

<?php
function phpcharset($data, $to)
{
    if (is_array($data)) {
        foreach ($data as $key => $val) {
            $data[$key] = phpcharset($val, $to);
        }
    } else {
        $encode_array = array(
            &#39;ASCII&#39;,
            &#39;UTF-8&#39;,
            &#39;GBK&#39;,
            &#39;GB2312&#39;,
            &#39;BIG5&#39;
        );
        $encoded      = mb_detect_encoding($data, $encode_array);
        $to           = strtoupper($to);
        if ($encoded != $to) {
            $data = mb_convert_encoding($data, $to, $encoded);
        }
    }
    return $data;
}
function toUTF8($data)
{
    return phpcharset($data, &#39;UTF-8&#39;);
}
function toGBK($data)
{
    return phpcharset($data, &#39;GBK&#39;);
}
function toASCII($data)
{
    return phpcharset($data, &#39;ASCII&#39;);
}
function toGB2312($data)
{
    return phpcharset($data, &#39;GB2312&#39;);
}
function toBIG5($data)
{
    return phpcharset($data, &#39;BIG5&#39;);
}
?>


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