IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

如何让 PHP json_encode 函数不转义中文?

idea's blog 2014-11-06 23:55:43 累计浏览 2,013 次
本机暂存

   如果你调用 PHP 自带的 json_encode() 函数, 碰到中文时, 中文会被转义掉. 例如:

echo json_encode(array('你好'));
// 输出: ["\u4f60\u597d"]

   这非常恼人, 像是一堆乱码, JSON 标准从来没有说要把非 ASCII 字符转义, 标准说的是”Any UNICODE character”.

   如何禁用掉这种转义呢? 答案是, PHP 自带的 json_encode() 不能禁用这个特性(在 5.4.0 版本之前), 你只能换一个新的 JSON 库. 为了简单, 我简单写了几十行代码, 实现一个 json_encode().

class Util
{
    static function json_encode($input){
        // 从 PHP 5.4.0 起, 增加了这个选项.
        if(defined('JSON_UNESCAPED_UNICODE)'){
            return json_encode($input, JSON_UNESCAPED_UNICODE);
        }
        if(is_string($input)){
            $text = $input;
            $text = str_replace('\\', '\\\\', $text);
            $text = str_replace(
                array("\r", "\n", "\t", """),
                array('\r', '\n', '\t', '\"'),
                $text);
            return '"' . $text . '"';
        }else if(is_array($input) || is_object($input)){
            $arr = array();
            $is_obj = is_object($input) || (array_keys($input) !== range(0, count($input) - 1));
            foreach($input as $k=>$v){
                if($is_obj){
                    $arr[] = self::json_encode($k) . ':' . self::json_encode($v);
                }else{
                    $arr[] = self::json_encode($v);
                }
            }
            if($is_obj){
                return '{' . join(',', $arr) . '}';
            }else{
                return '[' . join(',', $arr) . ']';
            }
        }else{
            return $input . '';
        }
    }
}

   考虑不到的地方, 例如判断关联数组(is_obj)的地方, 遇到问题再说. 你要是不喜欢类, 那就自己转成纯函数, 换个名字吧.

同分类推荐文章

  1. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,270)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,164)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,408)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,150)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 12,791)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,541)
  7. Redis消息队列的若干实现方式 (累计阅读 12,088)
  8. 到底什么是MVC? (累计阅读 11,870)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 11,709)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,488)