In PHP development, it's common to convert arrays to JSON format strings for data interaction with the front-end or data storage. PHP's built-in json_encode function converts arrays to JSON format, but by default, it only supports UTF-8 encoding. To support other encodings like GBK, we need to create a custom recursive function to convert arrays to JSON.
Ensure your PHP version is above 5.4, as PHP introduced the second parameter options in the json_encode function starting from version 5.4, which allows for more flexible configurations.
To support GBK encoding, you need to install the mbstring extension. This extension provides functions for handling multibyte strings. You can install it with the following command:
sudo apt-get update
sudo apt-get install php-mbstring
Next, let's create a custom recursive function to convert the array to JSON. Here is the function implementation:
/**
* Convert array to JSON string (supporting GBK encoding)
* @param array $array Array to be converted
* @return string JSON formatted string
*/
function json_encode_gbk($array) {
$array = array_map('urlencode_gbk', $array);
$json = json_encode($array);
return urldecode_gbk($json);
}
/**
* Encode string to GBK
* @param string $str String to be encoded
* @return string Encoded string
*/
function urlencode_gbk($str) {
return urlencode(mb_convert_encoding($str, 'GBK', 'UTF-8'));
}
/**
* Decode string from GBK
* @param string $str String to be decoded
* @return string Decoded string
*/
function urldecode_gbk($str) {
return mb_convert_encoding(urldecode($str), 'UTF-8', 'GBK');
}
The json_encode_gbk function first uses array_map to process each element of the array with the urlencode_gbk function. Then, it uses json_encode to convert the array into a JSON string. Finally, the urldecode_gbk function decodes the string, converting it from GBK back to UTF-8.
Suppose we have an array containing Chinese characters:
$array = array(
'姓名' => '张三',
'年龄' => 25,
'性别' => '男'
);
We can convert this array to JSON using the json_encode_gbk function:
$json = json_encode_gbk($array);
echo $json;
The output will be:
{
"姓名": "张三",
"年龄": 25,
"性别": "男"
}
As shown above, the Chinese characters have been successfully converted to Unicode encoding.
By creating a custom recursive function, we have successfully implemented array-to-JSON conversion with support for GBK encoding. In real-world development, you can use a similar approach to extend the functionality for other encodings.
The core idea behind the custom recursive function is to encode the array elements before converting, and then decode them afterward. This ensures proper conversion between different encodings.
We hope this article helps you understand how to create a custom recursive function in PHP for array-to-JSON conversion.