<?php $a = array('city' => "北京\"'\abcd天津"); echo json_encode($a) . "\n"; ?> debian-test-server:/home/php# php test1.php {"city":"\u5317\u4eac\"'\\abcd\u5929\u6d25"}现在有这样一个需求,数据库中某个字段可以保存多个值,这样需要将数据用json编码以后保存在数据库中,用php内置的json_encode函数处理以后中文变成了unicode码(比如{"city":"\u5317\u4eac\"'\\abcd\u5929\u6d25"}),虽然网页上面能正确处理,但是从手机同步过来的数据是汉字(比如{"city":"北京\"'\\abcd天津"}),而不是unicode,为了从两个地方传递过来的数据在数据库中以相同的编码存储,现在暂时考虑将unicode码转换为汉字或是自定义一个json_encode函数,此函数不会将中文转换为unicode码。
在PHP的官方网站上面找到一个函数,可以解决上述所说的需求,也就是将数据转换json,而且中文不会被转换为unicode码。
/** * 由于php的json扩展自带的函数json_encode会将汉字转换成unicode码 * 所以我们在这里用自定义的json_encode,这个函数不会将汉字转换为unicode码 */ function customJsonEncode($a = false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. return floatval(str_replace(",", ".", strval($a))); } if (is_string($a)) { static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } else { return $a; } } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = customJsonEncode($v); return '[' . join(',', $result) . ']'; } else { foreach ($a as $k => $v) $result[] = customJsonEncode($k).':'.customJsonEncode($v); return '{' . join(',', $result) . '}'; } }就直接调用使用上面的函数就可以的了!