多字节 Unicode 字符 – 永夜 https://www.shuijingwanwq.com 没有不值得去解决的问题,也没有不值得去学习的技术! Mon, 26 Feb 2024 01:45:02 +0000 zh-Hans hourly 1 https://wordpress.org/?v=7.0 在 PHP 中,插入 json 字符串至 MySQL 中,中文已经被编码后的处理 https://www.shuijingwanwq.com/2024/02/26/8449/ https://www.shuijingwanwq.com/2024/02/26/8449/#respond Mon, 26 Feb 2024 01:45:02 +0000 https://www.shuijingwanwq.com/?p=8449 浏览量: 70 1、在 PHP 中,插入 json 字符串(其中的中文已经被编码)至 MySQL 中,中文已经被编码。如图1
在 PHP 中,插入 json 字符串(其中的中文已经被编码)至 MySQL 中,中文已经被编码。

图1



insert into
  `table` (
    `column`,
  )
values
  (
    '{\"custom\":\"\",\"result\":{\"ack\":\"false\",\"attr1\":\"\",\"attr2\":\"\",\"channel_code\":\"\",\"childList\":[],\"delay_type\":\"\",\"is_changenumbers\":\"\",\"is_delay\":\"\",\"is_remote\":\"\",\"is_residential\":\"\",\"label_url\":\"\",\"message\":\"%E7%94%B3%E6%8A%A5%E4%BB%B7%E5%80%BC%E5%BF%85%E9%A1%BB%E5%A4%A7%E4%BA%8E0\",\"order_id\":\"\",\"order_privatecode\":\"\",\"order_transfercode\":\"\",\"orderpricetrial_amount\":\"\",\"orderpricetrial_currency\":\"\",\"post_customername\":\"\",\"product_tracknoapitype\":\"\",\"reference_number\":\"\",\"return_address\":\"\",\"tracking_number\":\"\"}}'
  )


2、尝试直接将整个 json 字符串进行 URL解码。而不是将 json 转换为数组,然后再遍历数组,将每一个值进行 URL解码,最后再将数组编码为 json 字符串。使用在线工具尝试 URL 解码,最后再格式化,格式化成功,发现此方案可行。如图2
尝试直接将整个 json 字符串进行 URL解码。而不是将 json 转换为数组,然后再遍历数组,将每一个值进行 URL解码,最后再将数组编码为 json 字符串。使用在线工具尝试 URL 解码,最后再格式化,格式化成功,发现此方案可行。

图2

3、最后在代码中实现如下


isset($result['transport_back_result']) ? urldecode($result['transport_back_result']) : ''


4、查看 MySQL 中的 json 字符串,确认中文已经被 URL解码,符合预期。如图3
查看 MySQL 中的 json 字符串,确认中文已经被 URL解码,符合预期

图3

5、但是,仍然存在请求参数中有中文未被正常显示的情况。原因在于请求参数是用 json_encode($requestParamsData) 实现的,然后返回。最终决定先 json 解码,再 json 编码,编码时添加参数 JSON_UNESCAPED_UNICODE。JSON_UNESCAPED_UNICODE 表示以字面编码多字节 Unicode 字符(默认是编码成 \uXXXX)。  


{"trade_type":"ZYXT","order_returnsign":"N","duty_type":"DDU","cargo_type":"B","consignee_name":"\u5ba2\u6237\u59d3\u540d"}





{
  "trade_type": "ZYXT",
  "order_returnsign": "N",
  "duty_type": "DDU",
  "cargo_type": "B",
  "consignee_name": "客户姓名"
}




json_encode(json_decode($str, true), JSON_UNESCAPED_UNICODE);




{"trade_type":"ZYXT","order_returnsign":"N","duty_type":"DDU","cargo_type":"B","consignee_name":"客户姓名"}


]]>
https://www.shuijingwanwq.com/2024/02/26/8449/feed/ 0