Home Backend Development PHP Tutorial Detailed explanation of PHP json_encode() function and Chinese garbled code problem

Detailed explanation of PHP json_encode() function and Chinese garbled code problem

Dec 27, 2016 pm 04:05 PM

Using the json_encode() built-in function in php (php > 5.2) can be used so that data in php can be transferred and used well with other languages.

The function of this function is to convert numerical values ​​into json data storage format.

<?php
$arr = array
  (
   &#39;Name&#39;=>&#39;希亚&#39;,
   &#39;Age&#39;=>
  );
$jsonencode = json_encode($arr);
echo $jsonencode;
?>
Copy after login

The program running result is as follows:

{"Name":null,"Age":}

json_encode function Chinese is encoded as null. I googled it and found that it is very simple. In order to closely integrate with the front-end, Json only supports utf- encoding. I think it is because the front-end Javascript is also utf-.

<?php
$array = array
 (
  &#39;title&#39;=>iconv(&#39;gb&#39;,&#39;utf-&#39;,&#39;这里是中文标题&#39;),
  &#39;body&#39;=>&#39;abcd...&#39;
 );
echo json_encode($array);
?>
Copy after login

The running result of this program is:

{"title":"\u8fd9\u91cc\u662f\u4e2d\u6587\u6807 \u9898","body":"abcd..."}

All Chinese characters in the array are missing or \u2353 etc. appear after json_encode.

The solution is to use the urlencode() function to process the following. Before json_encode, use urlencode() to process all the contents of all arrays, then use json_encode() to convert it into a json string, and finally use urldecode () Convert the encoded Chinese back.

<?php
/**************************************************************
 *
 * 使用特定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)
{
 static $recursive_counter = ;
 if (++$recursive_counter > ) {
  die(&#39;possible deep recursion attack&#39;);
 }
 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]);
   }
  }
 }
 $recursive_counter--;
}
/**************************************************************
 *
 * 将数组转换为JSON字符串(兼容中文)
 * @param array $array  要转换的数组
 * @return string  转换得到的json字符串
 * @access public
 *
 *************************************************************/
function JSON($array) {
 arrayRecursive($array, &#39;urlencode&#39;, true);
 $json = json_encode($array);
 return urldecode($json);
}
$array = array
  (
   &#39;Name&#39;=>&#39;希亚&#39;,
   &#39;Age&#39;=>
  );
echo JSON($array);
?>
Copy after login

It was successful this time, the running results are as follows:

{"Name":"Xia","Age":"20 "}

The following will introduce to you the solution to Chinese garbled characters in PHP json_encode

I believe that many people have encountered the problem of Chinese garbled characters when using Ajax to interact with the background php page. As a lightweight data exchange format, JSON is very popular. However, using PHP as the background interaction is prone to the problem of Chinese garbled characters. JSON is the same as js. The characters on the client are processed in the form of UTF8. That is to say, when using JSON as the data format for submission and reception, the characters are processed by UTF8 encoding. When our page encoding and database encoding are not When using UTF8, it is extremely easy for Chinese garbled characters to appear. The solution is naturally to use UTF8 when processing JSON data with js or PHP.

PHP5.2 or above uses json_encode as a built-in function, which brings great convenience to website makers. However, we must note that json_encode only supports UTF8-encoded characters. Otherwise, Chinese characters will be garbled. Or a null value appears.

The solution is divided into the following two steps.

Step1

Ensure that characters are encoded in UTF8 when processing JSON. Specifically, we can change both the database encoding and page encoding to UTF8. Of course, if you like to use gbk encoding, you can convert the characters to UTF8 before JSON processing. There are the following methods in PHP:

<?php
  $data="JSON中文";
  $newData=iconv("GB2312","UTF-8//IGNORE",$data);
  echo $newData;
  //ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符都不会被保存。
  //或是("GB2312","UTF-8",$data);
?>
Copy after login

Step2

Backend PHP page (the page is encoded as UTF-8 or the characters have been converted to UTF -8) Use json_encode to convert the array array in PHP into a JSON string. For example:

<?php
 $testJSON=array(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
 echo json_encode($testJSON);
?>
Copy after login

The output result is:

{"name":"\u4e2d\u6587\u5b57\u7b26\u4e32″, "value":"test"}

It can be seen that even if UTF8-encoded characters are used, Chinese garbled characters appear when using json_encode. The solution is to use the urlencode() function to process the characters before using json_encode, then json_encode them, and use the urldecode() function to convert them back when outputting the results. The details are as follows:

<?php
 $testJSON=array(&#39;name&#39;=>&#39;中文字符串&#39;,&#39;value&#39;=>&#39;test&#39;);
 //echo json_encode($testJSON);
 foreach ( $testJSON as $key => $value ) {
  $testJSON[$key] = urlencode ( $value );
 }
 echo urldecode ( json_encode ( $testJSON ) );
?>
Copy after login

Check the output result:

{"name":"Chinese string","value":"test ”}

At this point, Chinese characters have been successfully output. Feel free to use json_encode. In this way, the JSON string output in the PHP background will not appear Chinese garbled when eval is received by Ajax in the front-end javascript, because js also processes JSON format data in the form of UTF8, which is similar to PHP, so it receives the PHP page The JSON string does not cause problems.


For more detailed explanations of the PHP json_encode() function and articles related to Chinese garbled characters, please pay attention to the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles