CodeIgniter中json_encode报Malformed UTF-8字符错误的解决求助
CodeIgniter中json_encode报Malformed UTF-8字符错误的解决求助
各位大佬好,我现在在CodeIgniter 4项目里遇到一个头疼的问题,执行到json_encode的时候总是抛出UTF-8字符格式错误,具体报错信息如下:
Fatal error: Uncaught CodeIgniter\Format\Exceptions\FormatException: Falha ao analisar a string json, erro: "Malformed UTF-8 characters, possibly incorrectly encoded". in C:\xampp\htdocs\sysbio\vendor\codeigniter4\framework\system\Format\JSONFormatter.php:41
这个错误出现在控制器的ajax_list方法里,代码如下:
public function ajax_list($status = 'all') { $retorno = [ 'status' => false, 'message' => 'Nenhum status válido foi informado para a busca de lotes.' ]; if (in_array($status, ['all', 'validos', 'expirados'])) { $codpro = $this->request->getVar('codpro', FILTER_SANITIZE_STRING); if (!empty($codpro)) { $retorno = [ 'status' => true, 'message' => null, 'lotes' => $this->E210dlsModel->getLotes($this->codEmpresa, $codpro, $status) ]; } else { $retorno['message'] = 'Nenhum lote encontrado para este produto.'; } } echo json_encode($retorno, JSON_UNESCAPED_UNICODE); }
经过排查,问题应该出在模型的getLotes方法调用findAll()的时候,数据从数据库取出来后就触发了这个UTF-8格式错误。我的E210dlsModel代码如下:
<?php namespace App\Models\Senior; use CodeIgniter\Model; class E210dlsModel extends Model { /** * Variável com o nome da tabela */ protected $table = 'e210dls'; /** * Variável com o formato desejado para os retornos do model */ protected $returnType = 'object'; /** * Variável que determina a a conexão com Banco de dados Senior */ protected $DBGroup = 'senior'; /** * @param array * @return array */ public function getLotes(int $codemp, string $codpro, string $status) { if ($status == 'validos') { $this->where('e210dls.datvlt >=', date('Y-m-d 00:00:00')); } elseif ($status == 'expirados') { $this->where(['e210dls.datvlt < ' => date('Y-m-d 00:00:00')]); } if (!empty($codpro)) { $data = $this->distinct(true) ->select('e210dls.codlot, e210dls.datfab, e210dls.datfab as datfaboriginal, e210dls.datvlt, e210dls.datvlt as datvaloriginal') ->where(['e210dls.codemp' => $codemp]) ->where(['e210dls.codpro' => $codpro]) //->whereIn('e075pro.tippro', ['P']) ->orderBy('e210dls.datvlt', 'ASC') ->findAll(); return $data; } } public function getLote(int $codemp, string $codpro, string $codlot) { if (!empty($codpro) && !empty($codlot)) { return $this->select('e210dls.codpro as produto, e210dls.codlot as lote, e210dls.datfab, e210dls.datvlt as datval') ->where(['e210dls.codpro' => $codpro]) ->where(['e210dls.codlot' => $codlot]) ->where(['e210dls.codemp' => $codemp]) ->where('e210dls.coddep', ['10']) ->first(); } } }
我已经尝试了各种方法来排查:
- 检查并确认数据库配置的字符集是
utf8,排序规则是utf8_general_ci - 重新梳理了模型的查询逻辑,甚至完全重构过模型代码
- 确认前端传参都是正确的,后端能正常接收参数
但问题还是没有解决,现在就是想从数据库里取出一批记录返回成JSON,却一直卡在这个UTF-8字符错误上。有没有大佬能给点思路或者解决方案?
内容来源于stack exchange
相关产品推荐
相关产品推荐

