Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php,如何;“安全”;JSON编码数组?_Php_Json_Utf 8 - Fatal编程技术网

Php,如何;“安全”;JSON编码数组?

Php,如何;“安全”;JSON编码数组?,php,json,utf-8,Php,Json,Utf 8,我以前认为这是100%: file_put_contents ('cacheHere', json_encode($array)); 但这仅仅是99%。它只能对utf8编码的数据进行编码,因此: file_put_contents ('cacheHere', json_encode(utf8_encode($array))); 它仍然不正常,因为$array是数组,而不是字符串。我知道我可以用utf8逐个对字段进行编码,但我需要一个通用的解决方案。使用array\u walk\u recur

我以前认为这是100%:

file_put_contents ('cacheHere', json_encode($array));
但这仅仅是99%。它只能对utf8编码的数据进行编码,因此:

file_put_contents ('cacheHere', json_encode(utf8_encode($array)));

它仍然不正常,因为$array是数组,而不是字符串。我知道我可以用utf8逐个对字段进行编码,但我需要一个通用的解决方案。

使用
array\u walk\u recursive
,并在回调中检查当前条目是否为字符串,带有
is\u string
。如果是,则对其进行编码,否则保持原样

json_encode (array_walk_recursive ($array, function (&$a) {
    if (is_string ($a)) {
        $a = utf8_encode ($a);
    }
}));

一般的解决方案是将数据放在UTF-8中。如果
utf8\u encode
对您有效,那么您的数据实际上是用ISO-8859-1编码的

如果数据来自数据库,并且您使用的是MySQL,那么您可以这样做,以使数据库结果以UTF-8而不是ISO-8859-1显示:

$mysqli->set_charset('utf8');
在提出任何疑问之前


这只是一个例子,它实际上取决于你从哪里获得数据。请参阅。

您确定首先需要
json\u encode()
吗?佩卡说了什么;这里,
序列化
/
取消序列化
可能是一个替代选项。这涉及到很多PHP的怪癖。+1是一个很酷的想法,但我更倾向于返回$a,而不是做那些通过引用传递的东西。那么解码呢?:)@user1929946忘记解码和编码,看看我的答案