When developing projects with ThinkPHP5.1, converting arrays to JSON strings is a common operation. However, sometimes you might encounter errors such as “data cannot be converted to JSON,” specifically json_encode reporting: Invalid UTF-8 sequence in argument. This error is usually caused by the presence of non-UTF-8 encoded characters in the array, such as GBK encoding used on Windows, while JSON requires all strings to be UTF-8 encoded.
There are two main ways to resolve this issue: converting character encoding with PHP’s built-in functions or using ThinkPHP’s own JSON conversion methods.
PHP’s iconv() function can convert strings from one encoding to another. For array elements that are not UTF-8 encoded, you can use iconv() to convert them to UTF-8 before calling json_encode(). Here is an example:
$array = array('name' => '张三', 'age' => 18, 'address' => '北京市xxx区xxx路'); $json_str = json_encode($array, JSON_UNESCAPED_UNICODE); // May cause error foreach ($array as $k => $v) { $array[$k] = iconv("GBK", "UTF-8", $v); } $json_str = json_encode($array, JSON_UNESCAPED_UNICODE); echo $json_str;
The code tries json_encode directly, which may fail due to encoding issues. Then, it converts each array element to UTF-8 with iconv and successfully encodes the array to JSON.
ThinkPHP5.1 provides a Json helper class that can directly convert arrays to JSON strings while handling encoding internally. Example:
use think\helper\Json; $array = array('name' => '张三', 'age' => 18, 'address' => '北京市xxx区xxx路'); $json_str = Json::encode($array); echo $json_str;
This method simplifies the process by eliminating the need for manual encoding conversions, and it is recommended for use in ThinkPHP projects.
Encoding issues are a common challenge when converting arrays to JSON. Errors from json_encode are often related to character encoding. Depending on your case, you can either use iconv() to convert encoding or ThinkPHP’s Json::encode method to ensure proper encoding and improve code efficiency. Mastering these methods helps prevent JSON conversion failures due to encoding problems during development.