PHP json函数遇到的字符编码问题

参考

json_decode produces error “Single unpaired UTF-16 surrogate in unicode escape” and returns null

PHP json_decode does not work with single unpaired surrogate caused by Node 12 well-formed JSON.stringify

php json函数只能支持utf-8编码

在调取其它语言接口时,json_decode报错Single unpaired UTF-16 surrogate in unicode escape

解决方法一

正则替换掉无效\u开头的unicode字符,然后json_decode

 $contents = preg_replace('/(?<!\\\)\\\u[a-f0-9]{4}/iu', '', $contents);
 $json = json_decode($contents, true);

解决方法二

自定义json_decode方法

 public function customJsonDecode($json)
    {
        $comment = false;
        $out = '$x=';

        for ($i = 0; $i < strlen($json); $i++)
        {
            if (!$comment)
            {
                if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
                else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
                else if ($json[$i] == ':') $out .= '=>';
                else
                    $out .= $json[$i];
            }
            else
                $out .= $json[$i];
            if ($json[$i] == '"' && $json[($i - 1)] != "\\")
                $comment = !$comment;
        }

        eval($out . ';');

        return $x;
    }