dongzhimin2231 2017-04-11 16:13
浏览 351
已采纳

由cURL发出的JSON在utf8mb4数据中有错误

I've a script in PHP that reads from a table in DDBB, set a JSON and send it by cURL but the endpoint receive characters like accents wrong (acutes).

1) Firstly, i connect to the bbdd and set the charset:

$conn=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) or die("Error " . mysqli_error($con));
mysqli_set_charset($conn,"utf8mb4");

The database collation is utf8mb4_unicode_ci, I can't change that.

2) I build the array with the info:

$arr_json = array();
$array_json['key'] = htmlentities("Más");
[...]

3) Once is settled, create the JSON from the array:

$arr_json = json_encode($arr_json,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

4) Finally, i send the info:

curl_setopt_array($curl, array(
      CURLOPT_URL => URL,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => $arr_json,
      CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "content-type: application/json",
      ),
    ));

I receive a 200 code, but the endoint of the API always receive wrong input, for example a previous value of:

'Más'

It would be:

'Más'

The PHP script file is UTF-8, and the info in database is correctly stored. Any ideas?

  • 写回答

1条回答 默认 最新

  • duanjiwu0324 2017-04-11 16:26
    关注

    JSON and CURL have nothing to do with this, you're explicitly escaping the characters here:

    $array_json['key'] = htmlentities("Más");
    

    That turns "Más" into 'Más'.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置