如何使用法语口音对数组进行 json_encode?

2022-01-07 00:00:00 json character-encoding php mysql

我有一个带有法国口音的数组项([WIPDescription] => Recette Soupe à lOignon Sans Boeuf US).正在从数据库 (mysql) 中正确提取数据.

I have an array item with a French accent ([WIPDescription] => Recette Soupe à lOignon Sans Boeuf US). The data is being properly pulled from the database (mysql).

但是,当我尝试使用 json_encode 中内置的 php 将其编码为 json 时,它会生成一个 null json 值(OS X 服务器:php 5.3.4,启用 json 1.2.1).

However, when I try to encode this as json using the php built in json_encode it produces a null json value (OS X server: php 5.3.4, json 1.2.1 enabled).

在 Linux 服务器中,描述在第一个重音字符之后被截断.

In a Linux server, the description is cut off after the first accent character.

我尝试了所有 json_encode 选项都没有成功.有什么建议吗?

I tried all the json_encode options with no success. Any suggestions?

谢谢.

推荐答案

json_encode 只想要utf-8.根据您的字符集,您可以使用 iconvutf8_encode before 在你的变量上调用 json_encode .可能使用 array_walk_recursive.

json_encode only wants utf-8. Depending on your character set, you can use iconv or utf8_encode before calling json_encode on your variable. Probably with array_walk_recursive.

根据要求,一种未完成的改变数组的方法,假设(1)它不包含对象,(2)数组键在ascii/下界,所以可以保持原样:

As requested, an unfinished way to alter an array, with the assumptions that (1) it doesn't contain objects, and (2) the array keys are in ascii / lower bounds, so can be left as is:

$current_charset = 'ISO-8859-15';//or what it is now
array_walk_recursive($array,function(&$value) use ($current_charset){
     $value = iconv('UTF-8//TRANSLIT',$current_charset,$value);

});

相关文章