Laravel 中的“格式错误的 UTF-8 字符,可能编码不正确”

2022-08-30 08:51:58

我正在使用Laravel(一个PHP框架)为移动设备编写服务,并以格式返回数据。在数据结果中,有一些字段编码为 。JSONUTF-8

以下语句

return JsonResponse::create($data); 

返回以下错误

InvalidArgumentException
HELP
Malformed UTF-8 characters, possibly incorrectly encoded

Open: /var/www/html/vendor/symfony/http-foundation/Symfony/Component/HttpFoundation/JsonResponse.php
        } catch (\Exception $exception) {
            restore_error_handler();

            throw $exception;
        }

        if (JSON_ERROR_NONE !== json_last_error()) {
            throw new \InvalidArgumentException($this->transformJsonError());
        }

我已更改:

return JsonResponse::create($data);

return JsonResponse::create($data, 200, array('Content-Type'=>'application/json; charset=utf-8' ));

但它仍然不起作用。

我该如何修复它?


答案 1

我编写此方法来处理 UTF8 数组和 JSON 问题。它适用于数组(简单和多维)。

/**
 * Encode array from latin1 to utf8 recursively
 * @param $dat
 * @return array|string
 */
   public static function convert_from_latin1_to_utf8_recursively($dat)
   {
      if (is_string($dat)) {
         return utf8_encode($dat);
      } elseif (is_array($dat)) {
         $ret = [];
         foreach ($dat as $i => $d) $ret[ $i ] = self::convert_from_latin1_to_utf8_recursively($d);

         return $ret;
      } elseif (is_object($dat)) {
         foreach ($dat as $i => $d) $dat->$i = self::convert_from_latin1_to_utf8_recursively($d);

         return $dat;
      } else {
         return $dat;
      }
   }
// Sample use
// Just pass your array or string and the UTF8 encode will be fixed
$data = convert_from_latin1_to_utf8_recursively($data);

答案 2

我在这里找到了这个问题的答案

就这么做

mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');

推荐