Home > Article > Backend Development > Use PHP's json_encode() function to convert an array or object to a JSON string and encode Chinese characters to UTF-8
Use PHP's json_encode() function to convert an array or object into a JSON string and encode Chinese characters into UTF-8
In PHP, we can use The json_encode() function converts an array or object into a JSON string. By default, the json_encode() function encodes Chinese characters into Unicode characters, but sometimes we want to encode Chinese characters into UTF-8 for better processing and display of Chinese characters. This article will introduce how to use PHP's json_encode() function to encode Chinese characters into UTF-8.
First, we create an array or object containing Chinese characters:
$data = array( 'name' => '张三', 'age' => 25, 'gender' => '男' );
Or we can also use an object:
class Student { public $name; public $age; public $gender; } $student = new Student(); $student->name = '张三'; $student->age = 25; $student->gender = '男';
Next, we can use json_encode() The function converts an array or object into a JSON string, and sets the parameters JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES to encode Chinese characters into UTF-8:
$json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
or use an object:
$json = json_encode($student, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
in the above code , the parameter JSON_UNESCAPED_UNICODE is used to disable the conversion of Chinese characters into Unicode characters, and the parameter JSON_UNESCAPED_SLASHES is used to disable escaping slash characters.
Finally, we can print out the JSON string to view the result:
echo $json;
In this way, we can get the JSON string encoded as UTF-8:
{"name":"张三","age":25,"gender":"男"}
By converting Chinese The character encoding is UTF-8, and we can ensure that the JSON string can transmit and display Chinese characters correctly.
Summary:
This article introduces how to use PHP's json_encode() function to convert an array or object into a JSON string and encode Chinese characters into UTF-8. By setting the parameters JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES, we can prohibit converting Chinese characters to Unicode characters and escaping slash characters. This ensures that the JSON string handles and displays Chinese characters correctly.
The above is the detailed content of Use PHP's json_encode() function to convert an array or object to a JSON string and encode Chinese characters to UTF-8. For more information, please follow other related articles on the PHP Chinese website!