PHP string encoding conversion

巴扎黑
Release: 2016-11-22 11:03:53
Original
1324 people have browsed it

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;);
}
?>
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!