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'.

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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备