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

WBOY
WBOYOriginal
2016-07-13 10:56:20958browse

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:
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