PHP中json_encode中文编码的问题_学习

本文介绍了一个自定义的JSON编码函数,该函数用于处理PHP中的JSON字符串,旨在防止将汉字转换为Unicode码,确保编码过程更加精确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**
     *  由于php的json扩展自带的函数json_encode会将汉字转换成unicode码
     *  所以我们在这里用自定义的json_encode,这个函数不会将汉字转换为unicode码
     */
    public 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)) {
                return floatval(str_replace(",", ".", strval($a))); //将变量转换为字段串类型
                //floatval() 将变量转换为浮点类型
            }
            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; //判断键值是否为自增长,也就是键值是从0开始自动添加的,不是自定义的
        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[] = $this->customJsonEncode($v);
            return '[' . join(',', $result) . ']';
        } else {
            foreach ($a as $k => $v)
                $result[] = $this->customJsonEncode($k) . ':' . $this->customJsonEncode($v);
            return '{' . join(',', $result) . '}';
        }
    }

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值