-
- $a = array('city' => "Beijing"'abcdTianjin");
- echo json_encode($a) . "n";
- ?>
- debian-test -server:/home/php# php test1.php
- {"city":"u5317u4eac"'\abcdu5929u6d25"}
Copy code
Requirements, a field in the database can save multiple values, so you need to The data is encoded in json and stored in the database. After processing with the built-in json_encode function of PHP, the Chinese becomes unicode code (such as {"city":"u5317u4eac"'\abcdu5929u6d25"}). Although the web page can process it correctly, but from The data synchronized from the mobile phone is Chinese characters (such as {"city":"Beijing"'\abcdTianjin"}), not unicode. In order to store the data passed from two places in the database with the same encoding, we will consider it for now. Convert unicode codes to Chinese characters or customize a json_encode function. This function will not convert Chinese characters into unicode codes.
I found a function on the official PHP website that converts data to json, and Chinese will not be converted into unicode.
-
-
/** - * Since the function json_encode that comes with PHP's json extension will convert Chinese characters into unicode codes
- * So we use the custom json_encode here. This function will not convert Chinese characters into unicode codes
- */
- 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) . '}';
- }
- }
$a = array('a' => array('c' => 'China\"'Country', 'd' => 'South Korea'), 'b' => 'Japan');
- echo customJsonEncode($a) . l ;
- $b = array(array('c' => 'China\"'Country', 'd' => 'South Korea'), 'Japan');
- echo customJsonEncode($b) . l;
- ?>
-
Copy code
output:
{"a":{"c":"China\"'country","d":"South Korea"},"b":"Japan"}
[{"c":"China\"'country","d":"South Korea"},"Japan"]
|