json_encode()
对我不起作用。为什么?我怎样才能让它发挥作用?
php
:
echo json_encode($arr);
javascript
:
var theResponse = JSON.parse(xmlHttp.responseText);
当我
alert()
响应,且响应包含 å、ä 或 ö 时,响应为 = NULL
请帮帮我...
UTF-8
。但我没有使用 iconv 或 mbstring。当我在将值放入
utf8_encode()
之前
array
所有值时,问题就解决了。
/**
* Change data-type from string to integar or float if required.
* If string detected then utf8_encode() it.
*/
function cast_data_types ($value) {
if (is_array($value)) {
$value = array_map('cast_data_types',$value);
return $value;
}
if (is_numeric($value)) {
if(strpos('.', $value)===false) return (float)$value;
return (int) $value;
}
return mb_convert_encoding((string)$value, 'UTF-8', 'ISO-8859-1');
}
json_encode (cast_data_types($data));
您可以使用
base64_encode
对原始数据进行编码,然后它将与
json_encode
一起使用。稍后运行
json_decode
后,您可以使用
base64_decode
解码字符串,您将获得未修改的原始数据。
使用
utf-8
函数将数组中的字符串转换为
utf8_encode($str)
。然后
json_encode
与JSON_UNESCAPED_UNICODE 选项:
$arr = json_encode($array, JSON_UNESCAPED_UNICODE);
$resultArray = array();
while($obj = MySQL_fetch_object($res)) {
$resultArray[] = $obj;
}
$result = json_encode($resultArray);
可以使用以下方式完成编码:
$resultArray = array();
while($obj = MySQL_fetch_object($res)) {
foreach($obj as $key => $value) {
if (!is_null($value)) {
$obj->$key = utf8_encode($value);
}
}
$resultArray[] = $obj;
}
$result = json_encode($resultArray);
必须包含
if is_null
,以便空字段(例如日期时间字段)在输出中保持为空。
$data
(在我的例子中)是一个文本值为ISO-8859-1的数组。下面的技巧准备
$data
与
json_encode
一起使用。
function toUtf8(&$v, $k) {
$v = utf8_encode($v);
}
array_walk_recursive($data, 'toUtf8');