Home Backend Development PHP Tutorial Solution to gbk Chinese garbled code passed by PHP array to JavaScript and json_encode_PHP tutorial

Solution to gbk Chinese garbled code passed by PHP array to JavaScript and json_encode_PHP tutorial

Jul 13, 2016 am 10:56 AM
encode gbk javascript json php Chinese Garbled characters array article of solve

The article introduces the solution to gbk Chinese garbled characters when PHP arrays are passed to JavaScript and json_encode. The following is the creation of a JSON function. This paragraph comes from a hero on the Internet

The code is as follows Copy code
 代码如下 复制代码

/**************************************************************
 *
*    使用特定function对数组中所有元素做处理
*    @param    string    &$array        要处理的字符串
*    @param    string    $function    要执行的函数
*    @return boolean    $apply_to_keys_also        是否也应用到key上
*    @access public
*
*************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
            $array[$key] = $function($value);
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
}

/**************************************************************
 *
*    将数组转换为JSON字符串(兼容中文)
*    @param    array    $array        要转换的数组
*    @return string        转换得到的json字符串
*    @access public
*
*************************************************************/
function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}

/***************************************************** **********
*
* Use a specific function to process all elements in the array
* @param string &$array The string to be processed
* @param string $function The function to be executed
* @return boolean $apply_to_keys_also Whether to also apply to keys
* @access public
*
*************************************************** ***********/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
foreach ($array as $key => $value) {
            if (is_array($value)) {
             arrayRecursive($array[$key], $function, $apply_to_keys_also);
          } else {
              $array[$key] = $function($value);
}

If ($apply_to_keys_also && is_string($key)) {
               $new_key = $function($key);
                  if ($new_key != $key) {
$array[$new_key] = $array[$key];
                   unset($array[$key]);
             }
         }
}
}
 代码如下 复制代码

$dbcnx = @mysql_connect ( "localhost", "root", "1234" );
if (! $dbcnx) {
    echo ("Unable to connect to the " . "database server at this time.");
    exit ();
}

if (! @mysql_select_db ( "pms" )) {
    echo ("Unable to locate the joke " . "database at this time.");
    exit ();
}

mysql_query ( "SET NAMES 'GB2312'" );

    $q=mysql_query("select * from ability where ALV = 1");
    while($row=mysql_fetch_array($q)){
     $array1[] = $row[AName];
}

/***************************************************** **********
*
* Convert array to JSON string (compatible with Chinese)
* @param array $array The array to be converted
* @return string The converted json string
* @access public
*
*************************************************** ***********/
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
Return urldecode($json);
}
Connect the database to get the value to the array $array1
The code is as follows Copy code
$dbcnx = @mysql_connect ( "localhost", "root", "1234" );
if (! $dbcnx) {
echo ("Unable to connect to the " . "database server at this time.");
exit ();
} if (! @mysql_select_db ( "pms" )) {
echo ("Unable to locate the joke " . "database at this time.");
exit ();
} mysql_query ( "SET NAMES 'GB2312'" ); $q=mysql_query("select * from ability where ALV = 1");
While($row=mysql_fetch_array($q)){
$array1[] = $row[AName];
}

The array array1 is passed to JavaScript to the array ability1

The code is as follows
 代码如下 复制代码


Copy code

 代码如下 复制代码

 
/* 处理json_encode中文乱码 */
$data = array ('game' => '冰火国度', 'name' => '刺之灵', 'country' => '冰霜国', 'level' => 45 );
echo json_encode ( $data );
echo "
";
$newData = array ();
foreach ( $data as $key => $value ) {
$newData [$key] = urlencode ( $value );
}
echo urldecode ( json_encode ( $newData ) );
?>
 

Another solution to json Chinese garbled code

If it’s in Chinese, be careful


Find a solution online:

echo "
"; $newData = array ();
The code is as follows
Copy code

 代码如下 复制代码

class myClass {
public $item1 = 1;
public $item2 = '中文';
function to_json() {
//url编码,避免json_encode将中文转为unicode
$this->item2 = urlencode($this->item2);
$str_json = json_encode($this);
//url解码,转完json后将各属性返回,确保对象属性不变
$this->item2 = urldecode($this->item2);
return urldecode($str_json);
}
}
$c = new myClass();
echo json_encode($c);
echo '
';
echo $c->to_json();
echo '
';
echo json_encode($c);
echo '
';
echo json_encode('胥');
?>

程序输出结果:

{"item1":1,"item2":"u4e2du6587"}
{"item1":1,"item2":"中文"}
{"item1":1,"item2":"u4e2du6587"}
"u80e5"
 

/* Process json_encode Chinese garbled characters */
$data = array ('game' => 'Ice and Fire Country', 'name' => 'Thorn Spirit', 'country' => 'Frost Country', 'level' => 45 ); echo json_encode ( $data );
foreach ( $data as $key => $value ) { $newData [$key] = urlencode ( $value ); } echo urldecode ( json_encode ( $newData ) ); ?> Later I asked others for advice and found that base64 encoding can also be used, but base64 encoding cannot be placed in the URL. Baidu explained this: Standard Base64 is not suitable for transmission directly in the URL, because the URL encoder will change the "/" and "+" characters in standard Base64 into the form of "%XX", and these "%" The number needs to be converted when it is stored in the database, because the "%" sign has been used as a wildcard character in ANSI SQL. However, my data is sent via POST and is not in the HTTP head, but in the message-body, so it is not affected. json_encode can only accept data in utf-8 format For example: 'Xu' becomes 'u80e5' after json_encode processing, and the Chinese part of the final json is replaced with unicode encoding. What we have to solve is to convert the object into json and ensure that the Chinese inside the object still appears as normal Chinese in json. Now it seems that only using json_encode cannot achieve the goal. My solution: first url-encode the Chinese field in the class (urlencode), then json-encode the object (jsonencode), and finally url-decode (urldecode) the json, which is the final json. The Chinese inside is still the same Chinese ! The test code is as follows:
The code is as follows Copy code
class myClass { <🎜> public $item1 = 1; <🎜> public $item2 = 'Chinese'; <🎜> function to_json() { <🎜> //url encoding, avoid json_encode converting Chinese to unicode <🎜> $this->item2 = urlencode($this->item2); $str_json = json_encode($this); //Decode the url and return each attribute after converting to json to ensure that the object attributes remain unchanged $this->item2 = urldecode($this->item2); return urldecode($str_json); } } $c = new myClass(); echo json_encode($c); echo '
'; echo $c->to_json(); echo '
'; echo json_encode($c); echo '
'; echo json_encode('襥'); ?> Program output result: {"item1":1,"item2":"u4e2du6587"} {"item1":1,"item2":"中文"} {"item1":1,"item2":"u4e2du6587"} "u80e5" Notes can be found at: http://www.bKjia.c0m/phper/php/42865.htm

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632186.htmlTechArticleThe article introduces the solution to gbk Chinese garbled characters when PHP arrays are passed to JavaScript and json_encode. The following is a function to create JSON, This paragraph comes from a certain hero on the Internet. The code is copied as follows...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

See all articles