zoukankan      html  css  js  c++  java
  • PHP中json_encode中文编码的问题

    php的json扩展自带的json_encode函数,如果对含有中文的字符进行编码时,会自动转换成unicode编码。

    <?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) . '}';
        }
    }

    $a = array('a' => array('c' => '中\\"\'国', 'd' => '韩国'), 'b' => '日本');
    echo customJsonEncode($a) . l;
    $b = array(array('c' => '中\\"\'国', 'd' => '韩国'), '日本');
    echo customJsonEncode($b) . l;

    output:
    {"a":{"c":"中\\\"'国","d":"韩国"},"b":"日本"}
    [{"c":"中\\\"'国","d":"韩国"},"日本"]
  • 相关阅读:
    SSLZYC 洛谷P2055 假期的宿舍
    SSLZYC 2601 (洛谷P1756)【24题】飞行员配对方案问题
    SSLZYC POJ 3264 平衡的阵容
    SSLZYC 2432 面积最大
    SSLZYC 2433 文件名排序
    Structure of a C program: Preprocessor directives (#include <stdlib.h>, #define)
    Basic vim Commands
    UNIX Copying Files Remotely Examples(scp/pscp)
    ssh command in Linux with Example
    UNIX Copying a File
  • 原文地址:https://www.cnblogs.com/rooney/p/2318445.html
Copyright © 2011-2022 走看看